How to serialize a large JSON object directly to HttpResponseMessage stream?

半城伤御伤魂 提交于 2020-01-02 05:48:09

问题


Is there any way to stream a large JSON object directly to the HttpResponseMessage stream?

Here is my existing code:

        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");

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.

I want to do the equivalent of what's described here for deserialization.


回答1:


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");


来源:https://stackoverflow.com/questions/39355593/how-to-serialize-a-large-json-object-directly-to-httpresponsemessage-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!