简体   繁体   English

从 Web 服务反序列化大型 JSON 对象(内存不足)

[英]Deserializing large JSON Objects from Web Service (Out of Memory)

I have a program that deserializes large objects from a web service.我有一个从 Web 服务反序列化大对象的程序。 After a webservice call and a 200, the code looks like this.在 webservice 调用和 200 之后,代码如下所示。

JsonConvert.DeserializeObject<List<T>>(resp.Content.ReadAsStringAsync().Result).ToList()

Sometimes while running this process I will get an aggregate exception which shows an inner exception as out of memory.有时在运行此过程时,我会得到一个聚合异常,该异常显示内部异常为内存不足。 I can't determine if it is the process of reading in the string of JSON data (which is probably awfully large) or the Deserializing that is causing this issue.我无法确定是读取 JSON 数据字符串(可能非常大)还是导致此问题的反序列化过程。 What I would like to do is break out the string and pull each JSON object back individually from the response and then deserialize it.我想做的是分解字符串并从响应中单独拉回每个 JSON 对象,然后对其进行反序列化。 I am just having trouble finding a way to only bring out one JSON object at a time from the response.我只是很难找到一种方法来一次只从响应中取出一个 JSON 对象。 Any suggestions are greatly appreciated!任何建议都非常感谢!

HttpClient client = new HttpClient();

using (Stream s = client.GetStreamAsync("http://www.test.com/large.json").Result)
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
    JsonSerializer serializer = new JsonSerializer();

    // read the json from a stream
    // json size doesn't matter because only a small piece is read at a time from the HTTP request
    Person p = serializer.Deserialize<Person>(reader);
}

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/web-services/rest contains a warning: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/web-services/rest包含警告:

Using the ReadAsStringAsync method to retrieve a large response can have a negative performance impact.使用 ReadAsStringAsync 方法检索大型响应可能会对性能产生负面影响。 In such circumstances the response should be directly deserialized to avoid having to fully buffer it.在这种情况下,应直接反序列化响应以避免必须完全缓冲它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM