How to return multidimensional array as JSON for jqPlot chart in ASP.NET MVC C #

json should be in this format:

var data = [ ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14], ['Out of home', 16],['Commuting', 7], ['Orientation', 9] ]; 

But in my action method, I cannot figure out how to build json to display in this format. Here is what I have:

 var json = new[] { new[] {"Pending", summaryData.Sum(a => (int)a.Pending).ToString() }, new[] {"Completed", summaryData.Sum(a => (int)a.Completed).ToString()} }; return Json(json, JsonRequestBehavior.AllowGet); 

Which returns the following JSON:

 [["Pending","146"],["Completed","914"]] 

This is close, except that they are quotes around numeric values, and jqPlot does not seem to like it. Unfortunately, if I try to do Int32.Parse (...) on it, I get an exception.

Any ideas how to do this best?

thanks

+6
source share
1 answer

I assume that the error you get when you try to use Int32.parse is something like "There is no better type for an implicitly typed array." When using an implicitly typed array and the values ​​in this array are of different types, the compiler does not know what type to output the array.

You can get around this error by telling the compiler the type of arrays:

 var json = new[] { new object[] {"Pending", summaryData.Sum(a => (int)a.Pending) }, new object[] {"Completed", summaryData.Sum(a => (int)a.Completed) } }; 

This should serialize the array the way you want.

Like jqPlot, the quotation marks around the number cause a problem because the plugin most likely required the second element in the array to be of type Number.

+4
source

Source: https://habr.com/ru/post/894153/


All Articles