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:

VP-1 Mock Up

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!):

2017-07-19_21-16-08

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:

private void cmdClear_Click(object sender, EventArgs e)
{
  txtDebugOutput.Text = string.Empty;
}

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):

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);
  }
}

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...

private void cmdDeserialise_Click(object sender, EventArgs e)
{
  debugOutput(txtInput.Text);
}

Yeah - amazing right?

giphy-downsized.gif

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

simple json

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...)

simplejson in editor

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:

complexJSON

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:

complexjson in editor

A final example

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

arrayJSON.png

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:

NuGet

Once in the Package Manager Console, type:

PM> Install-Package newtonsoft.json

See below:

nugert success

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

jsonnet 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:

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

Now update the click event of our deserialize button:

 
private void cmdDeserialise_Click(object sender, EventArgs e) 
{ 
  deserialiseJSON(txtInput.Text); 
} 

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:

 
private void deserialiseJSON(string strJSON)
{
 try
 {
   var jPerson = JsonConvert.DeserializeObject<dynamic>(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());
 }
}

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:

examppl1

Success!

To Come

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

 

 

Advertisements

6 thoughts on “Deserializing JSON with c#

  1. This was very well done and the pace of the video was just right. I enjoyed the detail of the explanations. When you described about JSON payload either missing objects or not having data, do you have any sites you recommend looking at how to account for this? I am new at JSON and trying to learn as much as I can. Thanks for the well explained post.

    Liked by 1 person

  2. Your tutorial rocked! We, up, above (?), do get it with an “s” or a “z” !

    I followed your tutorial pretty well, but my JSON string has a nested array (apparently one more level down than your examples) and its giving me fits. Can you add something on deeper nested arrays?

    Thanks. (btw, I won’t be quitting my day job anytime soon. The programming is just a hobby).

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s