If you happen to head over to https://www.nuget.org/packages and look at which package has been downloaded the most there is a clear winner: JSON.net. It is in everything, every where. JSON is so wildly ubiquitous that I play a little game with myself when I start a new project: how long can I go before I need to serialize or deserialize JSON and need to pull in JSON.net. I rarely last more than a couple of hours.
But it turns out that there is a lot more that JSON.net can do.
My good buddy Eric Fleming found this one and I'm really just stealing it from him(although James claims he found it). The problem that we were trying to solve was that we wanted to patch together a new JSON object out of a bunch of C# objects. It could have been done by building a new DTO, mapping a number of objects to it and then serializing it to JSON. This was kind of a lot of work. Static languages are nice but chucking together ad hoc objects isn't a strong suit. In this case we used JObject to structure the new object
The output looks like
This approach can be useful in a number of scenarios
- Treating an object as a mixin and applying it to a bunch of differently shaped JSON
- Merging existing JSON with C# objects
The latter scenario can be achieved like so
There are also
JObject.Read for reading from JSON streams.
Newtonsoft.JSON is such a well known and well developed library that it is a shame to just use
JsonConvert methods when there is such additional richness.