Now a days JSON is widely used to exchange data due to it's simplicity and light-weight, so in this article, I am going to provide you with example with code to read JSON data in C#, I will be using ASP.NET MVC and Console appliction example for it.

You can use the C# code for any of your application whether it's C# console application, windows application or ASP.NET web-application, so in this article, I am going to provide you sample code using ASP.NET MVC & Console application.

Read JSON data in C# in MVC

In this article, i will perform following steps:

  1. Get sample JSON
  2. Create a class file for JSON.
  3. Deserialize JSON using DeserializeObject & save it as step 2creates class list.
  4. Print JSON in the View using Model.

Step 1: Before we proceed for any of the steps, your need to create a ASP.NET MVC sample project in your Visual Studio, so navigate to File-> New -> Project-> Select "Web" from left pane & "ASP.NET web application" (right-pane), name it and Click "OK"

read-json-data-using-chsarp-min.png

After clikcing OK new windows will appear, let's select "MVC" template from it to generate basic MVC configuration automatically for our project.

Step 2: Get the sample JSON, here is the sample JSON, which I will be using 

{
	"name": "John Smith",
	"sku": "20223",
	"price": 23.95,
	"shipTo": {
		"name": "Jane Smith",
		"address": "123 Maple Street",
		"city": "Pretendville",
		"state": "NY",
		"zip": "12345"
	},
	"billTo": {
		"name": "John Smith",
		"address": "123 Maple Street",
		"city": "Pretendville",
		"state": "NY",
		"zip": "12345"
	}
}

Note: You can always validate your JSON using website like JSONLint

Considering above JSON, we can create a C# class to save data in it and then use it as Model and print it in a View.

To do that you can use Visual-studio's  "Paste as Special" feture which is useful to convert, so using the sample provided in the post "Quick Tip to convert JSON into class object", Create a Class "JSONModel.cs" in Models folder of your project and then copy the above sample JSON, navigate to Edit -> Paste Special -> Paste JSON as Classes as shown in the below image.

how-to-read-json-data-in-csharp-min.png

Then your C# class will be as below

namespace ReadJSONusingCsharp.Models
{
    public class JSONModel
    {
        public class Rootobject
        {
            public string name { get; set; }
            public string sku { get; set; }
            public float price { get; set; }
            public Shipto shipTo { get; set; }
            public Billto billTo { get; set; }
        }

        public class Shipto
        {
            public string name { get; set; }
            public string address { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
        }

        public class Billto
        {
            public string name { get; set; }
            public string address { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
        }

    }
}

Now, go to your project's HomeController and inside Index ActionMethod, use the C# code below to Deserialize JSON and convert it into Class Model.

using Newtonsoft.Json;
using ReadJSONusingCsharp.Models;
using System.Web.Mvc;

namespace ReadJSONusingCsharp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //get JSOn string
            var json = "{ \"name\": \"John Smith\", \"sku\": \"20223\",\"price\": 23.95," +
                "\"shipTo\": { \"name\": \"Jane Smith\", \"address\": \"123 Maple Street\", \"city\": \"Pretendville\",\"state\": \"NY\", \"zip\": \"12345\" }, " +
                "\"billTo\": {\"name\": \"John Smith\",\"address\": \"123 Maple Street\",\"city\": \"Pretendville\",\"state\": \"NY\",\"zip\": \"12345\" }}";

            //Convert JSON into Model
            JSONModel.Rootobject records = JsonConvert.DeserializeObject<JSONModel.Rootobject>(json); //  JSON.Net

            //return data as Model to view
            return View(records);
        }
    }
}

and inside the Index.cshtml view use the Model to get data and print it as HTML.

@model ReadJSONusingCsharp.Models.JSONModel.Rootobject
@{
    ViewBag.Title = "Home Page";
}

<p>
    After reading JSON, it's output is as below
</p>

<p>Name : @Model.name</p>
<p>SKU: @Model.sku</p>
<p>Price : @Model.price</p>
<hr />
<p>Ship to name : @Model.shipTo.name</p>
<p>Ship to address: @Model.shipTo.address</p>
<p>Ship to City: @Model.shipTo.city</p>
<p>Ship to State: @Model.shipTo.state</p>
<p>Ship to Zip: @Model.shipTo.zip</p>
<hr />

<p>Billed to name : @Model.billTo.name</p>
<p>Billed to address: @Model.billTo.address</p>
<p>Billed to City: @Model.billTo.city</p>
<p>Billed to State: @Model.billTo.state</p>
<p>Billed to Zip: @Model.billTo.zip</p>

Build and run it in browser, you will get output as below

read-json-data-in-asp-net-mvc-min.png

Read JSON data in C# using Console Application.

We will be following same procedure as use in MVC project, create a new Console application project by navigating to File -> new-> project -> select "Window Classic desktop" (Left-pane) & "Console App"(from right-pane) , provide and a name ("ReadJSONInCharp") and click "OK"

We would have to create class same as JSONModel.cs in MVC project, so right click on your project in the solution, Select "Add"-> Select "Class" , name it as "JSONModel.cs" and use the below C# code

namespace ReadJSONInCharp
{
    public class JSONModel
    {
        public class Rootobject
        {
            public string name { get; set; }
            public string sku { get; set; }
            public float price { get; set; }
            public Shipto shipTo { get; set; }
            public Billto billTo { get; set; }
        }

        public class Shipto
        {
            public string name { get; set; }
            public string address { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
        }

        public class Billto
        {
            public string name { get; set; }
            public string address { get; set; }
            public string city { get; set; }
            public string state { get; set; }
            public string zip { get; set; }
        }

    }
}

One extra step in this would be to install NewtonSoft.JSON in your project usin Nuget package manager, navigate to "Tools"-> "Nuget Package manager"-> Select "Manage nuget packages for solution..." and click on "Browse" tab, the search "NewtonSoft.JSON" and select it and install in your project

newton-soft-json-read-csharp-example-console-application-min.png

Go to the main Program.cs file and use the code below

using Newtonsoft.Json;
using System;

namespace ReadJSONInCharp
{
    class Program
    {
        static void Main(string[] args)
        {

            var json = "{ \"name\": \"John Smith\", \"sku\": \"20223\",\"price\": 23.95," +
                "\"shipTo\": { \"name\": \"Jane Smith\", \"address\": \"123 Maple Street\", \"city\": \"Pretendville\",\"state\": \"NY\", \"zip\": \"12345\" }, " +
                "\"billTo\": {\"name\": \"John Smith\",\"address\": \"123 Maple Street\",\"city\": \"Pretendville\",\"state\": \"NY\",\"zip\": \"12345\" }}";
            JSONModel.Rootobject record = JsonConvert.DeserializeObject<JSONModel.Rootobject>(json); //  JSON.Net

            Console.WriteLine("JSON details");
            Console.WriteLine(record.name);
            Console.WriteLine(record.price);
            Console.WriteLine(record.sku);
            Console.WriteLine();

            Console.WriteLine("Ship to details");
            Console.WriteLine(record.shipTo.name);
            Console.WriteLine(record.shipTo.address);
            Console.WriteLine(record.shipTo.city);
            Console.WriteLine(record.shipTo.state);
            Console.WriteLine(record.shipTo.zip);
            Console.WriteLine();

            Console.WriteLine("Bill to details");
            Console.WriteLine(record.billTo.name);
            Console.WriteLine(record.billTo.address);
            Console.WriteLine(record.billTo.city);
            Console.WriteLine(record.billTo.state);
            Console.WriteLine(record.billTo.zip);

            Console.ReadLine();
        }
    }
}

Build and run your application, you will get output as below

how-to-read-json-data-using-csharp-console-application-min.png

That's it we are done, but there can be times when your JSON object is dynamic, so let's look on another example.

Read Dynamic JSON data in C#

Now, supopose your JSON is dynamic, so you cannot create it's class, so how you would access it without Model?

I will be using the answer provided in this question here "How to convert dynamic JSON string into C# class?", which looks useful to me, so from the answer, if your JSON is as below

{
	"Items": [{
			"Name": "Apple",
			"Price": 12.3
		},
		{
			"Name": "Grape",
			"Price": 3.21
		}
	],
	"Date": "21/11/2010"
}

You can Deserliaze it as dynamic object and then access data as you access arrays

dynamic DynamicData = serializer.Deserialize(jsonString, typeof(object));

DynamicData.Date; // "21/11/2010"
DynamicData.Items.Count; // 2
DynamicData.Items[0].Name; // "Apple"
DynamicData.Items[0].Price; // 12.3 (as a decimal)
DynamicData.Items[1].Name; // "Grape"
DynamicData.Items[1].Price; // 3.21 (as a decimal)

There are several other method provided in the above question's answer, another one is as below

dynamic details= JObject.Parse("{ 'Name': 'Jaya', 'Address': { 'City': 'New Delhi', 'State': 'Delhi' }, 'Age': 31}");

string name = details.Name; //GET Name
string address = details.Address.City; //Get City

We are done with sample's, if you have any questions please feel free to comment below.