加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:35:20 所属栏目:百科 来源:网络整理
导读:有没有办法将大型 JSON对象直接流式传输到HttpResponseMessage流? 这是我现有的代码: Dictionarystring,string hugeObject = new Dictionarystring,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");

哪个适用于较小的物体.但是,调用JsonConvert.SerializeObject()将对象转换为字符串的过程会导致大对象出现有问题的内存峰值.

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读