mvc return JsonArray as Json

放肆的年华 提交于 2019-12-23 23:37:37

问题


I'm trying to return a dynamic json array to the client side in mvc.

So far I have

            var a = 1;
            var b = 10;
            var jsonArray = new JArray();

            for (var i = 1; i < 5; i++)
            {
                var json = new JObject();
                json.Add("field" + a, b);

                jsonArray.Add(json);
                a++;
                b++;
            }

            return Json(jsonArray);

this returns to the client

[[[[]]]]

I have tried converting the JsonArray to a string first and setting it to have no formatter, but that doesn't return valid json according to fiddler.

I'd expect the result to be soemething like:

[{field1:10},{field2:11},{field3:12}]

Can anyone point out what I'm doing wrong


回答1:


This passed muster in Fiddler:

return Json(new { JsonArray = jsonArray.ToString() });

Fiddler seems to need JSON objects in the form { "FieldName": value }, hence my creation of an anonymous object. You could use any name in place of JsonArray.

Simply returning Json(jsonArray) isn't going to work because jsonArray will have an underlying representation that is dissimilar to your desired output, hence the output you are seeing when you serialize it.



来源:https://stackoverflow.com/questions/13562734/mvc-return-jsonarray-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!