I want to generate json string like this in C# language
{
"error": "0",
"message": "messages",
"data": {
"version": "sring",
"1": [
{
"keyword": "",
"title": ""
},
{
"keyword": "",
"title": ""
}
],
"2": [
...
],
"3": [
...
]
}
}
there is a problem here, "1":[{},{}],how to generate this part? I'm using asp.net mvc project by the way, I want to return this json string to the client web browser.
This response can be simply generated using Dictionary<string, object> with arrays as values.
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
});
It generates:
{
"error" : "0",
"message" : "messages",
"data" : {
"version" : "sring",
"1" : [{
"keyword" : "",
"title" : ""
}, {
"keyword" : "",
"title" : ""
}, {
"keyword" : "",
"title" : ""
}
]
}
}
If it is your API, then it is a good idea to extract version in order to make all objects in data be of the same type, and keys of type int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With