JSON

Deserializing JSON with c#


Foreword

This tutorial details how to deserialize* a JSON “string” into a c# object using JSON.net by Newtonsoft. It’s a stand alone tutorial, but follows logically from Consuming a REST API from c#.

* It pains me to use a ‘z’ here but I need to keep the US audiences and search engines happy!

If you prefer video to the written word, you can find the accompanying YouTube video here:

User Story

As a developer
I want to parse, (deserialize), a JSON string
So that I can work with c# objects

Acceptance Criteria

By the end of this tutorial you should be able to:

  • Understand what JSON is and how it’s structured
  • Deserialize JSON Strings

Ingredients

  • Windows PC (to run Visual Studio)
  • Visual Studio (I use the Community Edition)
  • JSON Editor Online @ http://jsoneditoronline.org/ (you can use an alternative I just like this one)
  • 20 Minutes of your time

User Interface Design

Using Balsamiq the following wire frame emerged and helped clarify my thinking, it’s pretty simple really… It takes and input, input is processed by clicking the button and the output is shown in the bottom plane. There’s a 2nd button that clears the output window.

A good wire frame should speak for its self though, so here you go:

Wire Frame – Realized

So here’s what the wire frame translates to in the real world, I’ve place the form element names there if you’re wanting to use the same naming convention as me, (not sure why you would my naming convention is pretty rubbish!):

Point to note, both textboxes are set to “Multiline: True” and with vertical scroll bars…

“Wire Up” The Buttons

Ok, so let’s do some simple stuff first, double click each button on the form designer to invoke their click event handlers.

Into the “cmdClear” button’s handler place the very simple code:

[code language="csharp"]
private void cmdClear_Click(object sender, EventArgs e)
{
  txtDebugOutput.Text = string.Empty;
}
[code]

If you don’t understand what that’s doing then you may struggle with the rest of the tutorial, so moving on!

I also, (as in previous tutorials), like to add my little “debugOutput” function that takes a string, displays it on a multi-line text box and “scrolls” to the next line, so further text can be displayed. So inside your Form code, add the following function, (it’s not mandatory for the actual parsing of JSON, but it just looks nice):

[code language="csharp"]
private void debugOutput(string strDebugText)
{
  try
  {
    System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
    txtDebugOutput.Text = txtDebugOutput.Text + strDebugText + Environment.NewLine;
    txtDebugOutput.SelectionStart = txtDebugOutput.TextLength;
    txtDebugOutput.ScrollToCaret();
  }
  catch(Exception ex)
  {
    System.Diagnostics.Debug.Write(ex.Message.ToString() + Environment.NewLine);
  }
}
[code]

Let’s test the function by adding the following code to the cmdDeserialise Click event handler. Test it by typing something in txtInput, and clicking cmdDeserialise…

[code language="csharp"]
private void cmdDeserialise_Click(object sender, EventArgs e)
{
  debugOutput(txtInput.Text);
}
[code]

Yeah – amazing right?

So what is JSON?

I’m going to guess if you’re reading this you have some idea… So I don’t really want to go over in vast detail what it is here as there are plenty of great written resources already, (check out the Wikipedia entry here).

What I do want to do though is labor some points that will come in useful when we start deserializing the raw JSON strings…

  • Stands for: “JavaScript Object Notation”
  • Open format used for the transmission of “object” data, (primarily), over the web.
  • It consists of attribute-value pairs, (see examples below)
  • A JSON Object can contain other “nested” objects

Anatomy of a Simple JSON Object

In the above example we have a “Person” object with 4 attributes:

  • firstname
  • lastname
  • age
  • isAlive

With the following respective values:

  • Roger [This is a string data-type and is therefore delineated by double quotes ‘ ” ‘ ]
  • Moore [Again this is a string and needs double quotes
  • 89 [Number value that does not need quotes]
  • false [Boolean value, again does not need the double quotes]

Paste this JSON into something like jsoneditoronline.org, and you can interrogate its structure some more, (possibly not that useful for such a simple object…)

A, (slightly), more complex example

As mentioned in the overview of JSON, an object can contain “nested” objects, observe our person example above with a nested address object:

Here we can see that we have a 5th Person object attribute, address, which does not have a standard value like the others, but in fact contains another object with 3 attributes:

  • streetAddress
  • city
  • postcode

The values of all these attributes contains strings, so no need to labor that point further!

This nesting can continue ad-nauseum

Again posting this JSON into our online editor yields a slightly more interesting structure:

A final example

Onto our last example which this time includes an array of phone number objects:

Note: I removed: “age” and “isAlive” attributes from the person object as well as the “postcode” attribute from the address object purely for brevity.

You’ll observe that we added an additional attribute to our Person object, “phonenNumbers”, and unlike the “address” attribute it’s contains an array of other objects as opposed to just a single nested object.

So What?

So why did I detail these JSON examples, we’ll firstly it was to get you familiar with JSON and some of its core constructs, specifically:

  • The start and end of an object: ‘ { } ‘
  • Attribute-Value pairs
  • Nested Objects, (or objects as attribute values)
  • Array of Objects

Personally on my JSON travels these constructs are the main one’s you’ll come across, and as far as an introduction goes, should give you pretty good coverage of most scenarios.

Secondly, we’ll be using these examples in deserializing JSON with JSON.Net, so lets’s get started on that!

Installing JSON.NET

The best way to install JSON.Net into your Visual Studio project, (i think), is to use the NuGet Package Manager Console. So in your project, do the following:

Once in the Package Manager Console, type:

PM> Install-Package newtonsoft.json

See below:

You should also be able to see JSON.Net in the list of Project References:

OK, We’re Ready to Code

In order to deserialize a JSON string we’re going to use the JsonConvert class from the JSON.Net framework, then use the DesrializeObject method, a link to the Newtonsoft web site can be found HERE, detailing this approach.

Let’s be Dynamic

Ok our first example requires the least coding, first create a new method in your form’s code called: deserialiseJSON, as follows:

[code language="csharp"] 
private void deserialiseJSON(string strJSON)
{
  try
  {
    // TO DO: Our deserialize code
  }
  catch(Exception ex)
  {
    debugOutput("We had a problem: " + ex.Message.ToString());
  }
}
[code]

Now update the click event of our deserialize button:

[code language="csharp"] 
private void cmdDeserialise_Click(object sender, EventArgs e) 
{ 
  deserialiseJSON(txtInput.Text); 
} 
[code]

This just means we’re almost ready to start deserializing!

Go Back to our deserialiseJSON method, and in our try block, add the following code:

[code language="csharp"] 
private void deserialiseJSON(string strJSON)
{
 try
 {
   var jPerson = JsonConvert.DeserializeObject(strJSON);
   
   debugOutput("Here's our JSON object: " + jPerson.ToString());
   debugOutput("Here's the First Name: " + jPerson.firstname);
 }
 catch(Exception ex)
 {
 debugOutput("We had a problem: " + ex.Message.ToString());
 }
}
[code]

So what have we done here?

  • Created a variable (var) called jPerson. This will hold our deserialised JSON object
  • Used the DeserializeObject method of the JsonConvert class
  • Used the “dynamic” object as a place holder for our “type” – more on this below
  • Passed in what ever serialized, “raw”, json string is in our first text box

It’s the use of dynamic that’s most interesting here. This basically tells Visual Studio that we’ll have to wait until run time before our object dependencies are resolved. In practice this means we can pass in any valid json string and the JSON/Net frameowrk will interpret and create a deserilaised c# object for us on the fly, (jPerson).

We can then access the attributes of jPerson, and treat it like a regular object.

So let’s run our app, and pass in our simple json example:

Success!

To Come

Still to write up the use of c# classes and supply those as our type.

WebSockets
Which is best? WebSockets or SignalR
REST API
Consuming a REST API from c#
Entity Framework
Introduction to Entity Framework