0

I am trying to find clear documentation on how to deserialize JSON data from an http response as it is written. I am using HttpClient like so:

using var client = new HttpClient(mySocketsHttpHandler);
// auth setup e.t.c....
var response = await client.GetAsync(url);
// get data from response message

Currently using bog standard way of reading the JSON (using Newtonsoft):

var json = await response.Content.ReadAsStringAsync();
var niceObject = JsonConvert.DeserializeObject<MyNiceObject>(json);

Works great but there are some scenarios where the result is particularly large (over the 85kb limit for the LOH, sometimes by a lot). I am trying to optimise and would like to deserialize the JSON as it comes in from the request. HttpResponse and HttpClient seems to be a bit of a black box, currently I am trying:

await using var stream = response.Content.ReadAsStreamAsync();
using var sr = new StreamReader(stream);
using var reader = new JsonTextReader(sr);
var serializer = new JsonSerializer();
var niceObject = serializer.Deserialize<MyNiceObject>(reader);

The idea is to avoid the allocation of a string variable and ideally to buffer sections of the response, as it comes in, live into the JSON reader. So is this:

  • Actually parsing the JSON as it comes in? Or is it blocking until the response is complete and the stream is fully allocated?
  • Is it even possible to parse JSON from a stream as it is written to?
  • If this is not at all the right approach, which is the least resource intensive approach?
Rob Sanders
  • 5,197
  • 3
  • 31
  • 58
  • _Is it even possible to parse JSON from a stream as it is written to?_ it doesn’t seem likely, as it’s not probable that the stream would arrive in parseable chunks. – stuartd Jan 26 '22 at 22:45
  • Your last code block that you are trying is what is recommended [here](https://stackoverflow.com/a/17788118/1202807). To do any better, it would have to be specific to the type of data. For example, [this question](https://stackoverflow.com/questions/43747477/how-to-parse-huge-json-file-as-stream-in-json-net) has some good answers, but specific to a list of objects. – Gabriel Luci Jan 26 '22 at 23:16

0 Answers0