(Print this page)

Using Json.Net
Published date: Saturday, January 25, 2014
On: Moer and Éric Moreau's web site

No Json.Net isn’t something new. This open source project started back in 2006 by James Newton-King and is still supported as we speak. The latest release was in October 2013.

The purpose of Json.Net is simply to serialize and deserialize any .Net object. It is so well done that it outperforms most other serializer, it supports conversion to/from XML and even offers LINQ-to-Json.

Requirements

I would say that Json.Net runs everywhere you can find .Net code (Framework 2.0 and later). Windows applications, WPF, Console, Silverlight, Windows Phone, Web apps. It even runs on Android if you are using Mono (MonoTouch and MonoDroid). It is really a great benefit to rely on the same library in any .Net++ projects.

Json.Net is available from NuGet and also as an old-style download and install package if you prefer from CodePlex.

The demo application

This month demo solution contains both a VB and a C# projects. The solution was created using Visual Studio 2013 targeting the .Net Framework 4.

Figure 1: The demo application in action

Documentation and samples

The documentation and many samples are available directly from James website.

Samples are short and to the point, very easy to understand and to insert in your own project.

There are two things I would like to be improved in the documentation:

  • a built-in search feature would be faster than going back to your favorite search engine
  • some indications about which platforms/versions are supported. At the top of any help page, you find the assembly name and the version but what if you are using an older version of the framework, how can you tell if the member you are looking is working for your version?

Some examples of code

My short demo application will simply demonstrate some mechanisms of the library.

First we need a class to serialize:

Public Class DemoClass

    Public FatherName As String

    Public DOB As DateTime

    Public Children As List(Of String)

End Class

With that class we can create an instance like this:

'initialize a test class
Dim dc As DemoClass = New DemoClass
dc.FatherName = "Eric Moreau"
dc.DOB = New DateTime(1970, 5, 28)
dc.Children = New List(Of String)({"Laurence", "Justine"})

We are now ready to serialize this object with Json. After the library has been referenced, serialization is only one line of code:

Dim result As String = JsonConvert.SerializeObject(dc, Formatting.None)

Notice the last argument, it indicates not to format the string. If the string is to store in a database or send to another process, you don’t need to format it.

If you prefer to get a more human-readable output, you can use this line of code instead:

result = JsonConvert.SerializeObject(dc, Formatting.Indented)

Only the last parameter has changed.

De-serializing is not more complex. As an example, this line deserialize the content of a file:

Dim dc As DemoClass = JsonConvert.DeserializeObject(Of DemoClass)(File.ReadAllText(filename))

Conversion to and/or from Json to XML is also very simple.

For example, this line takes a Json string a convert it to a XML node:

Dim xml As XNode = JsonConvert.DeserializeXNode(json, "MyRootNode")

And converting XML back to Json is also a one-liner:

json = JsonConvert.SerializeXNode(xml, Formatting.Indented)

There is much more you can do with the library.

Using Json with Google Finance

I have been asked lately to query Google Finance to retrieve stock prices of foreign stocks. I found that a Json string is returned. You can call the service with a query like: http://www.google.com/finance/info?q=msft.

The Json response returns something like this:

// [ { "id": "358464" ,"t" : "MSFT" ,"e" : "NASDAQ" ,"l" : "36.38" ,"l_fix" : "36.38" ,"l_cur" : "36.38" ,"s": "0" ,"ltt":"4:00PM EST" ,"lt" : "Jan 17, 4:00PM EST" ,"c" : "-0.51" ,"c_fix" : "-0.51" ,"cp" : "-1.38" ,"cp_fix" : "-1.38" ,"ccol" : "chr" } ]

I am not really sure why but Google adds // in front of the returned string which we need to remove. The string, because it is surrounded with [] means that it is in fact an array of Json string.

As you can see, the string returned by Google is not very explicit on the name of the fields (for example, t stands for Ticker). This allows to transfer less data and get a bit more performance. Does that means that the class needs a property named t? Not at all. You can use the JsonProperty attribute to change the name of the value that will appear in your serialized string to something different (usually shorter) than what you are using in your code. This is often useful when you have to deserialize something sent by a provider without meaningful property names. It is also useful when you are serializing a large volume and you want to save some space.

We can create a class like this one to deserialize one stock price (notice that I am using the JsonProperty attribute):

Public Class GoogleStock

    <JsonProperty("t")>
    Public Ticker As String

    <JsonProperty("e")>
    Public Exchange As String

    <JsonProperty("l")>
    Public Price As Decimal

End Class

This code, parses this return into an object:

'remove unwanted characters
json = json.Replace("//", "")

'in fact, the string returned is an array
Dim array = JArray.Parse(json)

'de-serialize the first item of the array
Dim stock As GoogleStock = array(0).ToObject(Of GoogleStock)()

'output results
lblResults.Text = ""
lblResults.Text += "Ticker = " + stock.Ticker + Environment.NewLine
lblResults.Text += "Exchange = " + stock.Exchange + Environment.NewLine
lblResults.Text += "Price = " + stock.Price.ToString() + Environment.NewLine

Notice here that the input string contains much more properties the one I am interested in. The library will just ignore properties not matching.

Likewise, when de-serializing, you can safely ignore some properties unless you pass the argument MissingMemberHandling.Error in which case an exception will be raised if a property is not found in the string to deserialize.

Conclusion

What I like about Json is that it is by nature less verbose compared to XML. When resources are important, Json serialization is a great option. The fact that we have a full library to support it means that you are not losing anything by using a compact formatting.

If you would like even more compact serialized output, notice that this library even support Bson (Binary Json). The result is not even more compact but also base 64 encoded which means that the file cannot be easily read by humans.


(Print this page)