noctonura
noctonura

Reputation: 13131

How to serialize a large JSON object directly to HttpResponseMessage stream?

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.

Upvotes: 4

Views: 2404

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129777

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

Upvotes: 1

Related Questions