1
Doubt on how to serialize to return this JSON.
I’m using the Flot library (http://www.flotcharts.org/) to display a chart. I can generate the charts.
In my view I’m wearing it like this :
$.ajax({
url: '/graficos/GeraTesteFlot',
method: 'GET',
dataType: 'json',
success: function (retorno) {
$.plot($("#divFlot"), [retorno], options);
}
});
But I’m having difficulty generating JSON in the correct format. I need a JSON like this :
[
{ label: "José", data: [[1, 2], [2, 5]] },
{ label: "Maria", data: [[1, 5], [2, 3]] }
]
And I try to generate it with the code below :
public JsonResult GeraTesteFlot()
{
// Exemplo de retorno desejado :
// É um array de series, e cada série tem uma label e um array de "data"
//
// Ex:
// [
// { label: "José", data: [[1, 2], [2, 5]] },
// { label: "Maria", data: [[1, 5], [2, 3]] }
// ];
List<object> series = new List<object>();
series.Add(new
{
label = "José",
data = new[] { new double[] { 1, 2}, new double[] { 2, 5} }
});
series.Add(new
{
label = "Maria",
data = new[] { new double[] { 1, 5}, new double[] { 2, 3} }
});
return Json(series, JsonRequestBehavior.AllowGet);
}
But this code returns me the JSON like this :
[
{ "label": "José", "data": [[1, 2], [2, 5]] },
{ "label": "Maria", "data": [[1, 5], [2, 3]] }
]
The problem is the ""
double quotes in the attributes name. Instead of "label": "José"
, need label: "José"
without the ""
in the label
.
How to do?
Are you sure the problem is
""
? The format{"chave": valor}
is the correct format for JSON. This giving some error in the console?– Wakim
@Wakim if I take the returned string and I take the quotes from the object name, here goes.
– Guilherme de Jesus Santos
I tried with Javascriptserializer() according to this answer http://answall.com/a/5971/155 from a similar question, but it was about Highcharts, but it didn’t roll. The generated string also contained double quotes in the object name.
– Guilherme de Jesus Santos
In another graphic, in the case of a pie chart, I used something similar but from a LINQ query and was generated in the format I want.
– Guilherme de Jesus Santos
@Wakim you were right. I only realized the error when I passed the question to PT.SO! My mistake was in returning in the Ajax function that was
$.plot($("#divFlot"), [retorno], options);
, in the question I had put the correct format, which is$.plot($("#divFlot"), retorno, options);
– Guilherme de Jesus Santos