6

The json needs to 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 can't figure out how to construct the json to be rendered in that 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 their are quotes around the numeric values and jqPlot doesn't seem to like it. Unfortunately if I try to do a Int32.Parse(...) on it I get an exception.

Any ideas how to best do this?

Thanks

1 Answer 1

4

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." 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks much. You were right about the exception (thanks for including that). Adding "object" was the key
Also worth noting for others landing here from Google - a 2 dimension array in C# like decimal[5,10] doesn't get you a 2 dimension array in JSON coming out of MVC, it gets you a single 50-item array. You need List<decimal[10]> to get it to come out as a 2 dimension array in JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.