-2

仅在非常大的集合上,以下行在服务器级别的 mscorlib.dll 处引发 OutofMemroyException

HttpResponseMessage  response;
response.Content= new StringContent(JsonConvert.SerializeObject(results), 
system.Encoding.UTF8, "text/json");

但是,以下序列化同一对象的方法不会产生此错误

Var serializer= new System.Web.Script.Serilaization.JavascriptSerializer() 
{MaxJsonLength = int.MaxValue};
response.Content= new StringContent(serializer.Serialize(results), 
system.Encoding.UTF8, "text/json")

但是,使用第二种方法时,客户端会引发错误:

无法反序列化当前的 json 数组,因为该类型需要 json 对象

所以我希望要么用第一种方法解决内存问题,要么弄清楚为什么第二种方法可以像第一种方法一样反序列化

谢谢

4

1 回答 1

-1

对于大量数据,您希望将其流式传输到客户端,这样您就不会尝试将整个数据保存在服务器上的内存中,这就是您的示例中发生的情况。

这是一篇关于如何使用 JsonTextWriter 和 JsonSerializer 直接写入响应流的好帖子,这将最大限度地减少内存占用。

http://www.bizcoder.com/returning-raw-json-content-from-asp-net-web-api

于 2019-07-09T23:24:26.200 回答