POST POST

MAY
3
2017

JSON.net not just for serialization

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Program
{
static void Main(string[] args)
{
var sock = new Sock{
Colour = "blue",
Size = "medium"
};
var shoe = new Shoe{
Material = "leather"
};
var ensemble = JObject.FromObject(sock);
ensemble.Merge(JObject.FromObject(shoe));
Console.WriteLine(ensemble.ToString());
}
}
class Sock{
public string Colour {get; set;}
public string Size {get; set;}
}
class Shoe{
public string Material{get; set;}
}

The output looks like

1
2
3
4
5
{
"Colour": "blue",
"Size": "medium",
"Material": "leather"
}

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

1
2
3
4
5
6
7
8
9
10
var hatJObject = JObject.Parse(@"
{
'HatSize': 'Large'
}
");
var ensemble = JObject.FromObject(sock);
var shoeJObject = JObject.FromObject(shoe);
shoeJObject.Merge(JObject.FromObject(shoeLace));
ensemble.Merge(shoeJObject);
ensemble.Merge(hatJObject);

This outputs

1
2
3
4
5
6
7
{
"Colour": "blue",
"Size": "medium",
"Material": "leather",
"LaceLength": 30,
"HatSize": "Large"
}

There are also JObject.Load and 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.


Simon Timms

Email Email
Web Web
Twitter Twitter
GitHub GitHub
RSS

Looking for someone else?

You can find the rest of the Western Devs Crew here.

© 2015 Western Devs. All Rights Reserved. Design by Karen Chudobiak, Graphic Designer