2015-11-23 55 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

相关问题