我想用C#语言生成这样的json字符串
{
"error": "0",
"message": "messages",
"data": {
"version": "sring",
"1": [
{
"keyword": "",
"title": ""
},
{
"keyword": "",
"title": ""
}
],
"2": [
...
],
"3": [
...
]
}
}
这里有个问题,"1":[{},{}],这部分如何生成?顺便说一句,我正在使用 asp.net mvc 项目,我想将此 json 字符串返回给客户端 Web 浏览器。
最佳答案
可以使用 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,那么最好提取 version
为了使所有对象在data
类型相同,键类型为 int
.
关于c# - 如何生成以整数为键的json字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868663/