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

Is there a way to pass a large JSON object directly to an 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 is great for small objects. However, the process of calling JsonConvert.SerializeObject () to convert an object to a string causes problematic outbreaks of memory for large objects.

I want to make the equivalent of what is described here for deserialization .

+4
source share
1 answer

You can try to use PushStreamContentand write to it 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");
+1
source

Source: https://habr.com/ru/post/1653829/


All Articles