2015-11-23 53 views
0

我要生成JSON字符串像這樣的C#語言如何使用整數作爲鍵生成json字符串?

{ 
    "error": "0", 
    "message": "messages", 
    "data": { 
    "version": "sring", 
    "1": [ 
     { 
     "keyword": "", 
     "title": "" 
     }, 
     { 
     "keyword": "", 
     "title": "" 
     } 
    ], 
    "2": [ 
     ... 
    ], 
    "3": [ 
     ... 
    ] 
    } 
} 

這裏有一個問題,「1」:[{},{}],如何產生這一部分?順便說一下,我正在使用asp.net mvc項目,我想將此json字符串返回到客戶端Web瀏覽器。

+2

你想讓他們成爲1,2,3等任何特定的原因? –

+1

我認爲newtonsoft.json dll幫助.. – null1941

回答

6

可以使用Dictionary<string, object>將數組作爲值簡單生成此響應。

public class KeywordTitle 
{ 
    public string keyword { get; set; } 
    public string title { get; set; } 
} 

public class Response 
{ 
    public string error { get; set; } 
    public string message { get; set; } 
    public Dictionary<string, object> data { get; set; } 
} 

var dictionary = new Dictionary<string, object> { 
    {"version", "sring"} 
}; 

dictionary.Add("1", new [] 
{ 
    new KeywordTitle { keyword = "", title = "" }, 
    new KeywordTitle { keyword = "", title = "" }, 
    new KeywordTitle { keyword = "", title = "" } 
}); 

JsonConvert.SerializeObject(new Response 
{ 
    error = "0", 
    message = "messages", 
    data = dictionary 
}); 

它產生:

{ 
    "error" : "0", 
    "message" : "messages", 
    "data" : { 
     "version" : "sring", 
     "1" : [{ 
       "keyword" : "", 
       "title" : "" 
      }, { 
       "keyword" : "", 
       "title" : "" 
      }, { 
       "keyword" : "", 
       "title" : "" 
      } 
     ] 
    } 
} 

如果這是你的API,那麼它是一個好主意,以便使所有對象在data是同一類型的提取version,和類型的鑰匙int

+0

非常感謝Yeldar,好主意。我會以您的答案爲解決方案。 – QigangZhong

3

如果您使用的是Newtonsoft.Json NuGet包,則序列化Dictionary<int, List<MyClass>>會得到您預期的結果。

4

NuGet獲取Json.NET。然後,在你MVC模型上的Array屬性

[JsonProperty(PropertyName="1")] 
public string[] YourProperty { get; set } 

時序列化數據JSONPropertyName值用於使用該data annotation

+1

它看起來像'1','2','3'是生成索引... –

0

使用Json.net和下面的屬性添加到屬性,你有什麼要修改的名稱:

[JsonProperty(PropertyName = "1")] 
public List<ObjectName> Objects { get; set; } 

欲瞭解更多信息,看看在serialization attributes

相關問題