What is JSON.NET?

JSON.NET is a very high-performance framework compared to other serializers for converting C# object into JSON string. It is created by James Newton-Kind. You can find more information about this framework from this link

Convert JSON to a C# Class

 As a web developer, I regularly write code to consume and create data in a JSON format. It's a simple and easy way to represent data as a string and if you work with JSON every day, you'll know how much easier it is to use than XML.

If you write most of your code in C# as I do, you may find that you are regularly creating C# class files manually. This can become tedious and often complex JSON structures can take some time to unwrap. However, there is a sneaky little trick that you can use in Visual Studio 2013 to automatically convert a JSON string to a C# class.

For example, let's take the JSON string below:

[
    {
        "BookingStatusType": "Suggested",
        "MonetaryValue": 20195,
        "Count": 35,
        "ConversionRate": 2.9
    },
    {
        "BookingStatusType": "Contacted",
        "MonetaryValue": 8035,
        "Count": 21,
        "ConversionRate": 4.8
    },
    {
        "BookingStatusType": "Introduced",
        "MonetaryValue": 6955,
        "Count": 15,
        "ConversionRate": 6.7
    },
    {
        "BookingStatusType": "Viewed",
        "MonetaryValue": 165,
        "Count": 1,
        "ConversionRate": 100
    },
    {
        "BookingStatusType": "Confirmed",
        "MonetaryValue": 165,
        "Count": 1,
        "ConversionRate": 0
    }
]

If you copy this string to your clipboard, and then navigate to Visual Studio, you can select Edit -> Paste Special -> Paste JSON as Classes.

Convert-Json-String-to-C#

The string above will simply be converted into a C# class like the one below:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string BookingStatusType { get; set; }
    public int MonetaryValue { get; set; }
    public int Count { get; set; }
    public float ConversionRate { get; set; }
}

Easy right!? Well, while Visual Studio does it's best to convert the JSON to a C# class, you may find that you need to slightly tweak the naming, but overall it converts really well. If you work with XML, the option to paste XML and convert to a C# class is also available. This new feature is a simple way to convert a JSON string to a C# class using the built-in features in Visual Studio.

If you aren't able to upgrade to the latest version of Visual Studio, there is a handy online tool that you can use to get around this. Take a look at json2csharp.com. Using the online tool, you simply paste your JSON string and it will convert it online for you.