【问题标题】:How to serialize a large JSON object directly to HttpResponseMessage stream?如何将大型 JSON 对象直接序列化为 HttpResponseMessage 流?
【发布时间】:2016-09-06 18:28:04
【问题描述】:

有没有办法将大型 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。

【问题讨论】:

  • 你能发布你的大对象的结构吗?
  • 添加了hugeObject的示例...
  • 您是否尝试过您链接的页面上的Manual Serialization 部分?
  • @krillgar 看起来很有希望,但我不知道该写什么。我可以为响应创建一个 StreamContent HttpContent,但我必须提供流。
  • 使用关注点分离,我会创建一个类,如JsonConvert 来处理转换过程。您应该为您的每个对象添加一个方法,如果您有它们可用于将该对象写入流。如果你正在研究Dictionary&lt;string, string&gt; 之类的东西,那么你显然没有这种能力,并且可以将其封装在新类中。

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


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 2014-01-28
    • 1970-01-01
    • 2011-05-02
    • 2018-09-08
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多