Blog Archives

Json.Net – serialization and deserialization APIs for Json format

Json has emerged as a new favorite data format to be sent over the wire. It is a thinner alternative to XML data format. In any integration project conversion of different data formats is the back bone of data communication. like XML Json is also compatible to any platform and easily convertible to native data types.

What is Json.Net?    It is a portable class library developed by James Newton King which helps you serialize and deserialize Json strings to .Net objects.  Once you include this library in your project you can use it’s built – in classes like  JsonConvert to serialize and deserialize objects. You can also use its Linq to Json APIs which is really helpful and will remind you of  Linq to XML.

Where do i get it from?   Download it from CodePlex.   Latest version is Json.Net 4.5. You can install it using Nuget package manager from Visual studio (10 onwards). I would recommend you to start using Nuget if you don’t have it already.

Why Json.Net?    Nobody is going to start using any new library just because it is new and sounds cool. Right?

In .Net paradigm, We already have few alternatives to serialize/deserialize json objects apart from new Json.Net.

1)      DataContract serialization                   2)  JavaScript Serialization

to read more about JavascriptSerializer for Json serialization please read my post on  JavascriptSerializer for Json

Hence, main reason why should you choose Json.Net over DataContract serializer and JavaScript Serializer   is its performance and features it provides.  There is a very useful feature comparison done among three serialization techniques . Check it out on Json.Net features comparison

In short below are the main features it provides. 

  1. Flexible JSON serializer for converting between .NET objects and JSON
  2. LINQ to JSON for manually reading and writing JSON
  3. High performance, faster than .NET’s built-in JSON serializers
  4. Write indented, easy to read JSON
  5. Convert JSON to and from XML
  6. Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone

How Json.Net can be used?       finally some code 🙂

Step 1. Download  it from CodePlex. or preferably install it using Nuget Package manager.

Step 2. Make sure your project has Newtonsoft.Json dll in your bin folder.

here, Product is a C# type.

public class Product
 {
public string Name { get; set; }
public DateTime ExpiryDate { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
 }

Converting a json string to C# product object.


public Product JsonToProductObject(string jsonString)
 {
var deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonString);
return deserializedProduct;
 }

Converting product object to json fromat string.

public string ProductObjectToJson(Product product)
 {
 string json =JsonConvert.SerializeObject</strong>(product);
 return json;
 }

Linq to Json: There are instances when we do not need to serialize the objects just want to read few properties of an object or json string. Just Like Linq to XML Json.Net library also provides you the awesome capability of querying the json objects using Linq.

Below code is taken from the James.NewtonKing official website. Beauty of the code is to have the same declarative syntax that Linq users are so fond of.

List<Post> posts = GetPosts();
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
// here is the output which is a json string
//{
//  "channel": {
//    "title": "James Newton-King",
//    "link": "http://james.newtonking.com",
//    "description": "James Newton-King's blog.",
//    "item": [
//      {
//        "title": "Json.NET 1.3 + New license + Now on CodePlex",
//        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "CodePlex"
//        ]
//      },
//      {
//        "title": "LINQ to JSON beta",
//        "description": "Annoucing LINQ to JSON",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "LINQ"
//        ]
//      }
//    ]
//  }
//}
// Now we can query to get
var categories =  from c in rss.PropertyValue<JObject>("channel")                                                          .PropertyValue<JArray>("item")                                                                            .Children<JObject>()                                                                                      .PropertyValues<JArray>("category")                                                                       .Children<string>()                                                                                       group c by c into g                                                                                       orderby g.Count() descending                                                                              select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)                                                                             {
Console.WriteLine(c.Category + " - Count: " + c.Count);                                                  }
// below is the output
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1

To understand the Json.Net library in detail, you can refer to the official Json.Net classes and APIs reference.

James Newton King had really made our lives easy with this cool library which is not only new but performs great when compared to existing serialization techniques. Hats off to him 🙂

Note: Examples and features are cited from the original json.Net website http://james.newtonking.com/