简体   繁体   English

如何在ASP.NET MVC C#中为jqPlot图表返回多维数组作为JSON

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

The json needs to be in this format: json需要采用以下格式:

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

But in my action method I can't figure out how to construct the json to be rendered in that format. 但在我的动作方法中,我无法弄清楚如何构造以该格式呈现的json。 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: 返回以下JSON:

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

This is close except that their are quotes around the numeric values and jqPlot doesn't seem to like it. 这很接近,除了它们是数字值周围的引号,jqPlot似乎不喜欢它。 Unfortunately if I try to do a Int32.Parse(...) on it I get an exception. 不幸的是,如果我尝试在其上执行Int32.Parse(...),我会得到一个异常。

Any ideas how to best do this? 任何想法如何最好地做到这一点?

Thanks 谢谢

I'm guessing the error you get when you try to use Int32.parse is something like "No best type found for implicitly-typed array." 我猜测你尝试使用Int32.parse时得到的错误就像“找不到隐式类型数组的最佳类型”。 When using an implicitly typed array and the values in that array are of different types, the compiler doesn't know what type to infer for the array. 使用隐式类型数组并且该数组中的值具有不同类型时,编译器不知道要为数组推断的类型。

You can get around the error by telling the compiler a type for the 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 it. 应该按照您希望的方式序列化数组。

As for jqPlot, the quotes around the number are causing a problem because the plugin most likely required the second item in the array to be of type Number. 至于jqPlot,数字周围的引号引起了问题,因为插件很可能需要数组中的第二项为Number类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM