Reputation: 3
I am new to JSON. I am trying to create below JSON format using C#:
series: {
name: "series1",
data: [[0,2],[1,3],[2,1],[3,4]]
}
I am struggling with the data
part. What should be my .NET code to achieve the above format?
Upvotes: 0
Views: 93
Reputation: 116108
List<int[]> arr = new List<int[]>()
{
new[]{0,2},new[]{1,3},new[]{2,1},new[]{3,4},
};
var obj = new { data = arr };
string json = JsonConvert.SerializeObject(obj);
OUTPUT: {"data":[[0,2],[1,3],[2,1],[3,4]]}
declare these classes (see http://json2csharp.com/)
public class RootObject
{
public Series series { get; set; }
}
public class Series
{
public string name { get; set; }
public List<List<int>> data { get; set; }
}
create an instance of RootObject
, fill the properties, and serialize it.
Upvotes: 2
Reputation: 26267
Use newtonsoft Json.net to serialize the objects, available via nuget or http://james.newtonking.com/json
Create the objects like this
var seriesContent = new Dictionary<string, object>
{
{"name", "series1"},
{"data", new[] {new[]{0,2},new[]{1,3},new[]{2,1},new[]{3,4}}}
};
var series = new Dictionary<string, object>
{
{"series", seriesContent}
};
var s = JsonConvert.SerializeObject(series);
s
will contain
{
"series": {
"name": "series1",
"data": [
[0, 2],
[1, 3],
[2, 1],
[3, 4]
]
}
}
Upvotes: 0