Out Of Memory exception when deserializing with JSON.net – Use Streams instead

O

Calling an api and deserializing the returned json into a type is something I have to do quite often.

I used to use the following:


If the JSON returned is large, we’ll often get an Out Of Memory Exception

From the docs

To minimize memory usage and the number of objects allocated, Json.NET supports serializing and deserializing directly to a stream.

To rectify this, we can instead use Streams

 

In my example, where the JSON has a nested ‘result’ element, you’ll also need a class to represent this (see TypeContainingMyResult above)