Nowadays JSON is widely used to exchange data due to its simplicity and light-weight, so in this article, I am going to provide you with an example with code to read and parse JSON data in C# (.NET/.NET Core), I will be using multiple examples, ASP.NET MVC and Console application,.NET Core and Dynamic JSON parse example.

You can use the C# code for any of your applications whether it's a C# console application, windows application, or ASP.NET web application.

Read JSON data in C# in MVC

In this article, I will perform the following steps:

  1. Get sample JSON
  2. Create a class file for JSON.
  3. Deserialize JSON using DeserializeObject & save it as step 2 creates a 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.

For this you need to install NewtonSoft.JSON package from NuGet in your application and then you can use the below C# Code.

string jsonString = "{\"Items\": [{\"Name\": \"Apple\",\"Price\": 12.3},{\"Name\": \"Grape\",\"Price\": 3.21}],\"Date\": \"21/11/2010\"}";

            dynamic DynamicData = JsonConvert.DeserializeObject(jsonString);

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

Output:

read-parse-json-c-sharp-min.png

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.

Read or Parse JSON in .NET 6

In .NET 6 we can use System.Text.Json namespace which enables DOM parsing, navigation and manipulation in a similar manner to Newtonsoft.Json using the new classes JsonObject, JsonArray, JsonValue, and JsonNode.

Here is the complete example for parsing JSON using .NET 6 in C#

using System.Text.Json;

string data = "{\"Items\": [{\"Name\": \"Apple\",\"Price\": 12.3},{\"Name\": \"Grape\",\"Price\": 3.21}],\"Date\": \"21/11/2010\"}";

JsonDocument doc = JsonDocument.Parse(data);
JsonElement root = doc.RootElement;

var names = new List<string>();
Enumerate(root);

void Enumerate(JsonElement element)
{
    if (element.ValueKind == JsonValueKind.Object)
    {
        foreach (var item in element.EnumerateObject())
        {
            if (item.Value.ValueKind == JsonValueKind.Object)
            {
                Enumerate(item.Value);
            }
            else if(item.Value.ValueKind == JsonValueKind.Array)
            {
                var root = item.Value;
                var u1 = root[0];
                var u2 = root[1];
                Console.WriteLine(u1);
                Console.WriteLine(u2);
                Console.WriteLine(u1.GetProperty("Name")); // Apple
                Console.WriteLine(u1.GetProperty("Price")); //12.3

                Console.WriteLine(u2.GetProperty("Name")); //Grape
                Console.WriteLine(u2.GetProperty("Price")); //3.21
            }
            else
            {
                Console.WriteLine(item.Value.GetRawText()); // 21/11/2010
            }
        }
    }
}

Here is the output

parse-json-net-core-csharp

Note: System.Text.Json does not automatically handle camelCase JSON properties when using your own code unlike MVC/WebAPI requests and the model binder, so you need to provide code for it

JsonSerializerOptions options = new JsonSerializerOptions
{        
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,  // set camelCase       
    WriteIndented = true                                // write pretty json
};

// pass options to serializer
var json = JsonSerializer.Serialize(jsonDataToSerialize, options);
// pass options to deserializer
var order = JsonSerializer.Deserialize<ModelClass>(json, options);

System.Text.Json is also available for .Net Framework and .Net Standard as a NuGet package.

You may also like to read:

jQuery Autocomplete Textbox in ASP.NET Core MVC

Import data from Excel to SQL Server

Read JSON file with Javascript