MVC返回JsonArray为JSON [英] mvc return JsonArray as Json
问题描述
我想一个动态的JSON数组中的MVC返回到客户端。
I'm trying to return a dynamic json array to the client side in mvc.
到目前为止,我有
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);
这返回给客户端
[[[[]]]]
我已经试过第一次转换JsonArray为字符串,并将其设置为没有格式化,但根据提琴手不返回有效的JSON。
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.
我期望的结果被soemething,如:
I'd expect the result to be soemething like:
[{field1:10},{field2:11},{field3:12}]
任何人都可以指出我在做什么错
Can anyone point out what I'm doing wrong
推荐答案
在此提琴手鼓起传递:
return Json(new { JsonArray = jsonArray.ToString() });
提琴手,似乎需要在表格JSON对象 {字段名:值}
,因此我的创作一个匿名的对象。你可以代替 JsonArray
使用任何名称。
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
.
简单地返回 JSON(JSONArray),其中
是行不通的,因为 jsonArray
将有一个潜在的再presentation是不同的,以你想要的输出,因此输出你看到的,当你把它序列化。
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.
这篇关于MVC返回JsonArray为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!