从Web服务反序列化大型JSON对象(内存不足) [英] Deserializing large JSON Objects from Web Service (Out of Memory)
问题描述
我有一个程序,可以反序列化Web服务中的大型对象.经过网络服务呼叫和200之后,代码如下所示.
I have a program that deserializes large objects from a web service. After a webservice call and a 200, the code looks like this.
JsonConvert.DeserializeObject<List<T>>(resp.Content.ReadAsStringAsync().Result).ToList()
有时,在运行此过程时,我会得到一个聚合异常,该异常将内部异常显示为内存不足.我无法确定是导致这个问题的原因是读取JSON数据字符串(可能很大)的过程或反序列化.我想做的是分解字符串,并从响应中分别拉回每个JSON对象,然后反序列化它.我只是在寻找一种方法来一次仅从响应中带出一个JSON对象的麻烦.任何建议,不胜感激!
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. 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. I am just having trouble finding a way to only bring out one JSON object at a time from the response. 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);
}
这篇关于从Web服务反序列化大型JSON对象(内存不足)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!