Codementor Events

How to Parse JSON into a C# Object

Published Feb 03, 2017
How to Parse JSON into a C# Object

In this tutorial I am going to show you how to parse JavaScript Object Notation (JSON) into .NET objects using C#.

What is JSON?

JSON is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. It is based on a subset of the JavaScript Programming Language: Standard ECMA-262 3rd Edition - December 1999.

For more information on JSON, visit www.json.org

Okay, let's begin!

Let's start with a simple JSON string. In most cases, you will get this string from a web service call. For the sake of this tutorial, we will do this manually.

var example1 = @"{""name"":""John Doe"",""age"":20}";

example1 is a simple JSON object with 2 fields: name and age.

In order to access the field(s) in this JSON string, we need to deserialize it into something C# can understand. This is where I would like to introduce the JavaScriptSerializer class, which is part of the System.Web.Script namespace.

var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(example1);

What this line does is it deserializes the string example1 into an object of type Dictionary<string, string>.

Once we have done that, we can access the fields like this:

JSONObj["name"]; // equals John Doe
JSONObj["age"]; // equals 20

Note: the Dictionary definition must match the types of the values in our JSON. "John Doe" is a string but 20 is an integer, so we have to use <string, string> and not <string, int>.

Okay, so we have deserialized it but you still have to reference it in a clunky way - object["field_name"] - so let's fix that!

First, create a class which matches the definition of your JSON. In our case, we need a class with a string property and an int property:

class Example1Model
{
    public string name { get; set; }
    public int age { get; set; }
}

And now, to deserialize our JSON into an object of that type:

var example1Model = new JavaScriptSerializer().Deserialize<Example1Model>(example1);

And to reference the fields:

example1Model.name; // equals John Doe
example1Model.age; // equals 20

As you can see, this is much cleaner! Your IDE will give you intellisense/auto-completion, type information and everything you would expect from a native type in .NET.

Show me more!

Our first example was great, but it was basic. Now let us handle a complex JSON string — how about a list of orders for a customer?

var example2 = @"{""custId"": 123, ""ordId"": 4567, ""items"":[{""prodId"":1, ""price"":9.99, ""title"":""Product 1""},{""prodId"":78, ""price"":95.99, ""title"":""Product 2""},{""prodId"":1985, ""price"":3.01, ""title"":""Product 3""}] }";

As in example 1, the first thing we need to do is to create your classes, which represent the data in JSON. Here, I created 2 classes — the CustomerOrderSummary is for the outer fields (custId and ordId) and a list of objects of type Item.

class Item
{
    public int prodId { get; set; }
    public double price { get; set; }
    public string title { get; set; }
}
class CustomerOrderSummary
{
    public int custId { get; set; }
    public int ordId { get; set; }
    public List<Item> items { get; set; }
}

And to deserialize the JSON we simply do:

var example2Model = new JavaScriptSerializer().Deserialize<CustomerOrderSummary>(example2);

And to reference the fields:

example2Model.custId; // equals 123
example2Model.ordId; // equals 4567
example2Model.items.Count; // equals 3
example2Model.items[0].price // equals 9.99

There you have it! You can now parse JSON into .NET objects using C#! If you would like to retrieve and read the JSON via Objective-C and Node.js, feel free to read these two articles: iOS QuickTip: Getting and Reading JSON Data from a URL and How to Use JSON files in Node.js

Other Useful references:

  • www.json.org
  • www.json2code.com
Discover and read more posts from Andrew Buchan
get started
post comments11Replies
J Prajapati
4 years ago

I loved the article for simplicity, I was thinking about how this tool (https://jsonformatter.org/json-to-csharp) was developed.

But after reading this article, it does make sense.

Sahil Monga
5 years ago

Thanks, very clearly explained.

Michael Lucas
5 years ago

This is a great example, thank you for this post. I have a question I have a similar application but my code isn’t reading the Array coming back from my Json post.

Show more replies