Generate C# Classes from JSON Responses

Well, as web developers, we are always dealing with JSON data which are coming from different sources. Either we are serialising our entities, or it’s coming from the external sources like third-party services and so on.

If the data is coming from an external source, one standard requirement is to always de-serialise it back to the data model to be able to process the data. Creating data model for JSON data is not the most exciting work in the world, especially when the data model is a bit nested and complex.

Fortunately, there is a very nice feature in Visual Studio which makes the life much more manageable. This feature is called Paste Special.

To take advantage, you first need to Copy the JSON data. Imaging there is JSON data as follow:

{
 "glossary": {
 "title": "example glossary",
 "GlossDiv": {
 "title": "S",
 "GlossList": {
 "GlossEntry": {
 "ID": "SGML",
 "SortAs": "SGML",
 "GlossTerm": "Standard Generalized Markup Language",
 "Acronym": "SGML",
 "Abbrev": "ISO 8879:1986",
 "GlossDef": {
 "para": "A meta-markup language, used to create markup languages such as DocBook.",
 "GlossSeeAlso": ["GML", "XML"]
 },
 "GlossSee": "markup"
 }
 }
 }
 }
}

And we require creating the data model for that. To do so, just Copy the data in memory and go to Visual Studio, create a new class (or an existing one where we intend to have our data model).

From the Edit menu in Visual Studio, select the Paste Special and from the submenu, Paste JSON As Classes.

Then, the data model will generate as follow:

public class Rootobject
 {
 public Glossary glossary { get; set; }
 }

public class Glossary
 {
 public string title { get; set; }
 public Glossdiv GlossDiv { get; set; }
 }

public class Glossdiv
 {
 public string title { get; set; }
 public Glosslist GlossList { get; set; }
 }

public class Glosslist
 {
 public Glossentry GlossEntry { get; set; }
 }

public class Glossentry
 {
 public string ID { get; set; }
 public string SortAs { get; set; }
 public string GlossTerm { get; set; }
 public string Acronym { get; set; }
 public string Abbrev { get; set; }
 public Glossdef GlossDef { get; set; }
 public string GlossSee { get; set; }
 }

public class Glossdef
 {
 public string para { get; set; }
 public string[] GlossSeeAlso { get; set; }
 }

As if by magic you see the initial data model has been created for us

As you may have noticed, there is one more option under Paste Special menu item, named Paste XML As Classes. This item does the same thing but for XML data. That means you need to copy your XML data to the memory and from the Paste Special menu item, choose Paste XML As Classes this time, to have your data model generated.

Original post ‘Paste Special’: a less well-known feature in Visual Studio

Parse JSON into a C# Object

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:

original article