In preparation of a talk I gave in Karlsruhe in May 2014 and will give in Nürnberg in July 2014, I decided to start a series of articles to ramp up the topics I'll cover during those conferences. Here's the second topic this talk will cover: JsonFx and Json.NET. You'll ultimately find the other parts here: 1-NodaTime 3-RestSharp and 4-TinyIoC.

Foreword

JSON (JavaScript Object Notation) is a format that cannot and should not be ignored anymore. Way lighter to use than XML and certainly as powerful, it is becoming a new standard for data description. Seamless to use with JavaScript, it used to be a bit more complex with different languages. Thanks to some wonderful Libraries, C# is not one of them.

I decided to handle both libs at once, because I use both depending on the context.

Both are OpenSource and available on Nuget:

>Install-Package Newtonsoft.Json
>Install-Package JsonFx

Json.NET

Json.NET is the most downloaded library on Nuget. It supports Windows, Silverlight, Windows Phone, Mono, MonoTouch and MonoDroid. It is for me "de facto" the .NET standard Library for manipulating JSON.

Serialization/Deserialization

TL;DR; Both Serialization and Deserialization to POCOs are Dead simple one liners...

Create a POCO, call the SerializeObject() function of the JsonConvert object... done.

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": ["Small", "Medium", "Large"]
//}

To Deserialize, feed the JsonConvert DeserializeObject() method a POCO Type and a Json String and you are done.

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': ['Action', 'Comedy']
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

LINQ to JSON

One of the drawbacks of the Deserialization described above is the necessity of a POCO object. In many situations it is necessary and recommended to use a POCO, but in some others you just want to extract some data and get it over with. For this, you can use the JObject API that was designed with LINQ in mind.

JObject jobj = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

// Intel
string cpu = (string)jobj["CPU"];    

As you can see we did not manipulate a POCO in this case. We get this JObject to work with, and we can hit it directly as if we were manipulating an array. Neat.

SchemaValidation

Define your schema and validate the parsed entities:

string schemaJson = @"{
  'description': 'A person',
  'type': 'object',
  'properties':
  {
    'name': {'type':'string'},
    'hobbies': {
      'type': 'array',
      'items': {'type':'string'}
    }
  }
}";

JsonSchema schema = JsonSchema.Parse(schemaJson);

JObject person = JObject.Parse(@"{
  'name': 'James',
  'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
// true

You don't have to write the Schema yourself. Have a look at Antony Scott's article Using JSON.NET to generate JsonSchema to get an idea how to let JSON.NET generate that for you.

Json.NET

Most of the time when I need Json handling, I'd go with Json.NET. It is clear and easy to use. I haven't had any surprises with it.

But sometimes I need something a tad more flexible and even with its JObject, Json.NET still can't beat the dynamic support of JsonFx.

JsonFx

JsonFx is also available on Nuget, it supports Windows, Silverlight, Windows Phone & Mono.

As I said earlied, the main problem I have with Json.NET is that I need a POCO to parse a JSON String properly. Whenever I need it quick-&-dirty, JsonFx's serialization to a dynamic object beats the JObject flat out.

var reader = new JsonReader();

string input = @"{
    "foo": true,
    "myArray": [42, false, "Hello!", null]
}";

dynamic output = reader.Read(input);
Console.WriteLine(output.myArray[0]); //42

Notice the .array. This is a typical call to a dynamic dictionary. Go wild an prototype with this, I assure you, you will love it.

Wrap Up

Both those libraries are very solid. Json.NET is clearly ahead and that's my weapon of choice, but JsonFx has an ace in its sleeve and I use it from time to time when I need this particular feature.

What is really interesting with Json.NET is that it has established itself as the .NET Reference for manipulating JSON, pushing Microsoft's implementation down. I wonder if it will become a part of the .NET Framework...

Sources