使用Request.CreateResponse返回JsonArray

时间:2013-09-26 09:43:00

标签: c# asp.net asp.net-mvc

我构建了一个ASP.NET Web Api。 现在,我已将项目更新为MVC 4 RC,但动态对象不再按预期工作了。

我有这个:

var Arr = new JsonArray();

foreach (var Post in Coll)
{
    dynamic Item = new JsonObject();
    Item.Header = Post.Header;
    Item.Body = Post.Body;
    Item.Language = Post.Language;
    Arr.Add(Item);
}

return Request.CreateResponse(HttpStatusCode.OK, Arr);

我得到的结果是(在浏览器中):

[{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]},{"Header":[],"Body":[],"Language":[]}]

在debugg中我得到:(对象Arr)

{[{"Header":"All distances","Body":"All distances are ","Language":"EN"},{"Header":...

为什么会有所不同?

(Coll是对象列表)

2 个答案:

答案 0 :(得分:0)

尝试使用它

  

返回Request.CreateResponse(HttpStatusCode.OK,Arr.ToArray());

这只是一个猜测,如果您在调试中可以看到它,那么当您添加到监视列表并且观察者显示它时,您可能会强制计算对象。然后.ToArray()也应该帮助你。

答案 1 :(得分:0)

我猜你没有在客户端解析Arr到json数据。 在客户端ajax方法中尝试这个:

 var obj = $.parseJSON(result);

结果是从服务器返回的值。 你可以得到如下数组的每个对象:

        $(obj).each(function () {       
      // alert($(this).attr('Header'));  
 });