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?
Daniel A.A. Pelsmaeker
50.8k21 gold badges118 silver badges162 bronze badges
-
How is the data stored in your C# code? What have you tried?clcto– clcto2014年02月17日 22:45:21 +00:00Commented Feb 17, 2014 at 22:45
-
2Well for starters that is not correct JsonEric Herlitz– Eric Herlitz2014年02月17日 22:45:43 +00:00Commented Feb 17, 2014 at 22:45
-
You can also use Json.NET to achieve this. It is a popular library for working with Json.Daniel A.A. Pelsmaeker– Daniel A.A. Pelsmaeker2014年02月17日 22:47:55 +00:00Commented Feb 17, 2014 at 22:47
2 Answers 2
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]]}
OR
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.
answered Feb 17, 2014 at 22:46
L.B
116k20 gold badges189 silver badges229 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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]
]
}
}
answered Feb 17, 2014 at 22:49
Eric Herlitz
26.4k28 gold badges117 silver badges167 bronze badges
Comments
lang-cs