返回带有 Request.CreateResponse 的 JsonArray
本文关键字:JsonArray CreateResponse Request 返回 | 更新日期: 2023-09-27 18:32:56
我构建了一个 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":[]}]
在调试中,我得到这个:(对象Arr)
{[{"Header":"All distances","Body":"All distances are ","Language":"EN"},{"Header":...
为什么不同?
(Coll 是一个对象列表)
尝试使用它
return Request.CreateResponse(HttpStatusCode.OK, Arr.ToArray());
这只是一个猜测,如果您可以在调试中看到它,那么当您添加到监视列表并且观察程序显示它时,您可能强制计算对象。然后。ToArray() 也应该对你有所帮助。
我想你没有在客户端将 Arr 解析为 json 数据。在客户端 AJAX 方法中尝试此操作:
var obj = $.parseJSON(result);
结果是从服务器返回的值。您可以获取数组的每个对象,如下所示:
$(obj).each(function () {
// alert($(this).attr('Header'));
});
我
遇到了同样的问题,我已经修复了它,以这种方式插入内容:
var response = req.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(MY_OBJECT, Formatting.Indented), Encoding.UTF8, "application/json");
return response;