如何序列化一个大的JSON对象直接到HttpResponseMessage流

本文关键字:对象 JSON HttpResponseMessage 序列化 一个 | 更新日期: 2023-09-27 18:05:50

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

我想做与这里描述的反序列化相同的事情

如何序列化一个大的JSON对象直接到HttpResponseMessage流

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