Question:
I have the following code in C#:
Dictionary<string, object> dataResult = new Dictionary<string, object>();
dataResult["data"] = new List<object[]>();
dataResult["name"] = i;
foreach (var item in query)
{
object[] values = new object[2];
values[0] = Convert.ToDecimal(item.ini) ;
values[1] = Convert.ToDecimal(item.ir);
((List<object[]>)dataResult["data"]).Add(values);
}
With it I generate the following JSON:
var data = [
{"TESTE2008",23.4,2},
{"TESTE2008",24.4,3},
{"TESTE2008",25.4,4},
{"TESTE2008",26.4,5},
{"TESTE2008",27.4,6},
{"TESTE2008",28.4,7},
{"TESTE2008",29.4,8},
{"TESTE2008",30.4,9},
{"TESTE2009",30.4,2},
{"TESTE2009",31.4,3},
{"TESTE2009",32.4,4},
{"TESTE2009",33.4,5},
{"TESTE2009",34.4,6},
{"TESTE2009",35.4,7},
{"TESTE2009",36.4,8},
{"TESTE2009",37.4,9},
];
and I would like the data to be formatted as follows:
series: [{
name: 'TESTE2008',
data: [[23.4,2],[24.4,3],[25.4,4],[26.4,5],[27.4,6],[28.4,7],[29.4,8],[30.4,9]
]},
{
name: 'TESTE2009',
data: [[30.4,2],[31.4,3],[32.4,4],[33.4,5],[34.4,6],[35.4,7],[36.4,8],[37.4,9]]},
});
How to change my code to produce the desired output?
Answer:
Try something along those lines, I'm not good at .net but I think it will generate the way you need
/*
[{ name: 'Huguinho', data: [7.0, 6.9, 9.5, 14.5, 18.2] },
{ name: 'Zezinho', data: [24.1, 20.1, 14.1, 8.6, 2.5] },
{ name: 'Luizinho', data: [17.9, 14.3, 9.0, 3.9, 1.0] }]
*/
var objVet = new object[] { new { name = "Huguinho", data = new object[] { 7.0, 6.9, 9.5, 14.5, 18.2 } },
new { name = "Zezinho", data = new object[] { 24.1, 20.1, 14.1, 8.6, 2.5 } },
new { name = "Luizinho", data = new object[] { 17.9, 14.3, 9.0, 3.9, 1.0 } }};
JavaScriptSerializer js = new JavaScriptSerializer();
string strJson = js.Serialize(objVet);
return strJson;