Programming Solutions

Your Source for Information

JSON to Object Conversion in C#

by Maeenul 6. November 2011 11:07

Often we need to parse a JSON string and convert it to Object.

In C#, we don't have any built-in library that provides us the functionality.

But using Newtonsoft.dll, we can do it easily.

There are two objects provided to handle JSON objects.

Newtonsoft.Json.Linq.JObject

Newtonsoft.Json.Linq.JArray

Using these two objects we can get the json objects and object properties from a JSON string.

We will have to add the reference of the Newtonsoft dll from Add Reference wizard of visual studio.

Then we will have to include the using directive.

using Newtonsoft.Json.Linq;

JSON string having some properties:

This example shows how to convert a json object that contains some properties. We have two properties named report_id and report_name.

First we have to parse the json string to JObject. Then we can access the properties as array index where the index will be the name of the property.

string json = @"{ report_id: ""1901"",

report_name: ""Product"" }";

 

JObject jsonObj = JObject.Parse(json);

 

string report_id = (string)(jsonObj["report_id"]);

 

string report_name = (string)jsonObj["report_name"];

 

JSON string containing array of strings:

It is pretty common that we will have a property in JSON object which is an array. In this example we see a property named item which is an array of strings.

We have to access the property in the same way but we will have to cast it to JArray.

When we got the JArray, we can easily access the items of the array using integer index.

 

string json = @"{ report_id: ""1901"",

report_name: ""Product"",

item: [""CAMERA"",""RADIO"",""MOBILE""]}";

 

JObject jsonObj = JObject.Parse(json);

string report_id = (string)(jsonObj["report_id"]);

string report_name = (string)jsonObj["report_name"];

JArray item_array = (JArray)jsonObj["item"];

string aItem = (string)item_array[2];

 

JSON string containing array of json objects:

If the array itself contains some json objects, then we will have to cast individual elements of the array as JObject.

After that we can access the properties of that individual json object as described earlier in this post.

string json = @"{ report_id: ""1901"",

report_name: ""Product"",

item: [

{id: 1, name: ""CAMERA""},

{id: 2, name: ""RADIO""},

{id: 3, name: ""MOBILE""}

]

}";

 

 

JObject jsonObj = JObject.Parse(json);

string report_id = (string)(jsonObj["report_id"]);

string report_name = (string)jsonObj["report_name"];

JArray item_array = (JArray)jsonObj["item"];

JObject aItem = (JObject)item_array[2];

 

string aItemName = (string)aItem["name"];

 

 

 

 


 

 

Tags: , , , ,

Category: JSON



Pingbacks and trackbacks (1)+

Add comment

biuquote
  • Comment
  • Preview
Loading

Alpha Tags