2016-09-06 47 views
4

有沒有什麼方法可以將大的JSON對象直接流到HttpResponseMessage流?如何將一個較大的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

你可以發佈你的大對象的結構? – stefankmitph

+0

增加了hugeObject的示例... – noctonura

+0

您是否嘗試鏈接該頁面上的[Manual Serialization](http://www.newtonsoft.com/json/help/html/performance.htm#ID3RBSection)部分? – krillgar

回答

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");