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

C# 如何将大型JSON对象直接序列化到HttpResponseMessage流?,c#,.net,json,json.net,httpclient,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

有没有办法将一个大型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");
Dictionary hugeObject=newdictionary();
//填充100000个键/值。每个字符串是32个字符。
HttpResponseMessage response=新的HttpResponseMessage(HttpStatusCode.OK);
response.Content=新的StringContent(
内容:JsonConvert.SerializeObject(hugeObject),
编码:encoding.UTF8,
mediaType:“应用程序/json”);
这对较小的对象很有效。但是,调用JsonConvert.SerializeObject()将对象转换为字符串的过程会导致大型对象的内存峰值出现问题

我想做与之等效的操作。

您可以尝试使用,并使用:


你能发布你的大对象的结构吗?添加了hugeObject的示例…你尝试过你链接的页面上的部分了吗?@krillgar这看起来很有希望,但我不确定该写什么。我可以为响应创建StreamContent HttpContent,但我必须提供流。使用关注点分离,我将创建一个类,如
JsonConvert
,以处理转换过程。如果可以将每个对象写入流,则应该向每个对象添加一个方法。如果您正在处理类似于
Dictionary
,那么您显然没有这种能力,可以将其封装在新类中。
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");