问题
Is there any way to stream a large JSON object directly to the HttpResponseMessage stream?
Here is my existing code:
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");
Which works fine for smaller objects. However, the process of calling JsonConvert.SerializeObject() to convert the object into a string is causing problematic memory spikes for large objects.
I want to do the equivalent of what's described here for deserialization.
回答1:
You could try using a PushStreamContent and write to it with a 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");
来源:https://stackoverflow.com/questions/39355593/how-to-serialize-a-large-json-object-directly-to-httpresponsemessage-stream