如何将大型JSON对象直接序列化为HttpResponseMessage流?

时间:2016-09-06 18:28:05

标签: c# .net json json.net httpclient

有没有办法将大型JSON对象直接流式传输到HttpResponseMessage流?

这是我现有的代码:

        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()将对象转换为字符串的过程会导致大对象出现有问题的内存峰值。

我想做相当于what's described here for deserialization

1 个答案:

答案 0 :(得分:1)

您可以尝试使用PushStreamContent并使用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");