如何直接将大型JSON对象序列化为HttpResponseMessage流? [英] How to serialize a large JSON object directly to HttpResponseMessage stream?
本文介绍了如何直接将大型JSON对象序列化为HttpResponseMessage流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将大型JSON对象直接流式传输到HttpResponseMessage流?
Is there any way to stream a large JSON object directly to the HttpResponseMessage stream?
这是我现有的代码:
Dictionary<string,string> hugeObject = new Dictionary<string,string>();
// fill with 100,000 key/values. Each string is 32 chars.
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(
content: JsonConvert.SerializeObject(hugeObject),
encoding: Encoding.UTF8,
mediaType: "application/json");
对于较小的对象,它可以很好地工作.但是,调用JsonConvert.SerializeObject()将对象转换为字符串的过程会导致大型对象出现问题的内存峰值.
Which works fine for smaller objects. However, the process of calling JsonConvert.SerializeObject() to convert the object into a string is causing problematic memory spikes for large objects.
我想做等效于此处反序列化的描述
推荐答案
您可以尝试使用 JsonTextWriter
:
You could try using a PushStreamContent
and write to it with a JsonTextWriter
:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new PushStreamContent((stream, content, context) =>
{
using (StreamWriter sw = new StreamWriter(stream, Encoding.UTF8))
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jtw, hugeObject);
}
}, "application/json");
这篇关于如何直接将大型JSON对象序列化为HttpResponseMessage流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文