Deserialize a nested json in c#

In this blog you will see how to deserialize a nested json data and display on page.

For example this is our JSON:

string jSon =

"{\"FirstName\":\"Raj Kumar\", " +

"\"LastName\":\"Choudhary\"," +

"\"Likes\":" +

"[" +

"{\"Sport\":\"FootBall\"},{\"Music\":\"Rock\"},{\"Food\":\"Italian\"},{\"Place\":\"Goa\"}" +

"]}";

We have two classes:

public class User

{

public string FirstName { get; set; }

public string LastName { get; set; }

public System.Collections.ObjectModel.Collection<Likes> Likes { get; set; }

}

public class Likes

{

public string Sport { get; set; }

public string Music { get; set; }

public string Food { get; set; }

public string Place { get; set; }

}

This is our HTML:

<form id="form1" runat="server">

<h1>User</h1>

<div>

First Name :

<label id="lblFirstName" runat="server"></label>

</div>

<div>

Last Name :

<label id="lblLastName" runat="server"></label>

</div>

<h1>Hobbies</h1>

<div>

Sport :

<label id="lblSport" runat="server"></label>

</div>

<div>

Music :

<label id="lblMusic" runat="server"></label>

</div>

<div>

Food :

<label id="lblFood" runat="server"></label>

</div>

<div>

Place :

<label id="lblPlace" runat="server"></label>

</div>

</form>

Code:

protected void Page_Load(object sender, EventArgs e)

{

string jSon =

"{\"FirstName\":\"Raj Kumar\", " +

"\"LastName\":\"Choudhary\"," +

"\"Likes\":" +

"[" +

"{\"Sport\":\"FootBall\"},{\"Music\":\"Rock\"},{\"Food\":\"Italian\"},{\"Place\":\"Goa\"}" +

"]}";

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

User user = serializer.Deserialize<User>(jSon);

if (user != null)

{

lblFirstName.InnerText = user.FirstName;

lblLastName.InnerText = user.LastName;

lblSport.InnerText = user.Likes[0].Sport;

lblMusic.InnerText = user.Likes[1].Music;

lblFood.InnerText = user.Likes[2].Food;

lblPlace.InnerText = user.Likes[3].Place;

}

}