In this post we will see how we can get a json string converted to a c# object. String parsing is not the solution for this problem as parsing the whole json string will be very difficult and lots of case may arise. So we will avoid this part using Newtonsoft dll. In fact Newtonsoft itself provides a way for converting json to a c# object. We will see here how we can achieve this. As we are going to use Newtonsoft dll, we have to add the reference and also have to include the namespace as below:
using Newtonsoft.Json;
First we will see how to convert a c# object to json string. Then we will discuss the reverse.
C# Object to JSON String Conversion:
Suppose we have a simple class named Customer with two properties, ID and name. The class definition looks like the following.
public class Customer
{
public int ID { get; set; }
public string name { get; set; }
}
Now we can instantiate the class and convert it to json string using the JsonConvert.SerializeObject.
Customer customer = new Customer() { ID = 1, name = "Maeenul" };
string json = JsonConvert.SerializeObject(customer);
The json string will look like this.
{"ID":1,"name":"Maeenul"}
In the above example, the attribute in the json string is created according to the name of the property of the class. But if we want to give a customized name for the json properties we can use the JsonProperty attribute before the properties of the class.
public class Customer
{
[JsonProperty(PropertyName = "customer_id")]
public int ID { get; set; }
[JsonProperty(PropertyName = "customer_name")]
public string name { get; set; }
}
Now we will get the following string when converted to json.
{"customer_id":1,"customer_name":"Maeenul"}
While converting a c# object to json string, the JsonConvert.SerializeObject function does not consider the private properties and methods of the object. The following class defintion includes a private property named salary and a method GetSalary(). While converting to json string these two will not be included. So we will get the same json string as before.
public class Customer
{
[JsonProperty(PropertyName = "customer_id")]
public int ID { get; set; }
[JsonProperty(PropertyName = "customer_name")]
public string name { get; set; }
private int salary;
public int GetSalary()
{
return salary;
}
}
Converted json string will be: {"customer_id":1,"customer_name":"Maeenul"} All the previous examples show a simple object. But we might have an array or a list of a specific type of objects in our class definition. The following class contains two properties and a public list of Customer objects. We have added three customer objects in the list and set this list to a shop object. We can convert this type of objects also in the same way as before.
public class Shop
{
[JsonProperty(PropertyName = "name")]
public string Name;
[JsonProperty(PropertyName = "id")]
public int ID;
public List<Customer> customerList;
}
var customer_list = newList<Customer>();
var maeenul = newCustomer() { ID = 1, name = "Maeenul" };
customer_list.Add(maeenul);
var sharif = newCustomer() { ID = 2, name = "Sharif" };
customer_list.Add(sharif);
var suzan = newCustomer() { ID = 3, name = "Suzan" };
customer_list.Add(suzan);
var shop = newShop(){ID=1, Name="A Shop"};
shop.customerList = customer_list;
var json = JsonConvert.SerializeObject(shop);
The output json stirng will be:
{"name":"A Shop","id":1,"customerList":[{"customer_id":1,"customer_name":"Maeenul"},{"customer_id":2,"customer_name":"Sharif"},{"customer_id":3,"customer_name":"Suzan"}]}
Converting JSON string to c# Object:
Now we go to the reverse direction. We have a json string, probably from an ajax call or similar, and we want to convert it to a c# object. We can use the JsonConvert.DeserializeObject<Type> function to achieve the goal. Before converting to a c# class, we have to have the class definition. Suppose we have the json string as below. Now we will have to define a class that fully fits for the json string. Then we can give the type of the class to the DeserializedObject function and we will get our json string converted to an instance of the Type.
var json_string = @"{""name"":""A Shop"", ""id"":1, ""customerList"":[{""customer_id"":1,""customer_name"":""Maeenul""},{""customer_id"":2,""customer_name"":""Sharif""},{""customer_id"":3,""customer_name"":""Suzan""}]}";
var obj = JsonConvert.DeserializeObject<Shop>(json_string);
The following screenshot shows that our obj object now is an instance of the Shop class filled with the values from the json string.


A more complex example: However complex our json string is, if we define the class appropriately we will be able to convert this json string to our c# object.
public class ReportSettings
{
public class SelectedItems
{
publicstring level;
publicList<string> items;
}
public List<string> row_elements;
public List<string> column_elements;
public List<string> filter_elements;
public List<string> measure_elements;
public List<SelectedItems> selected_items;
}
var json_string = @"{""row_elements"":[""[Product].[ATC3].[ATC3]""],
""column_elements"":[""[Period].[Month].[Month]""],
""filter_elements"":[],
""measure_elements"":[""[Measures].[PTH_abs]""],
""selected_items"":[{""level"":""[Period].[Month].[Month]"",""items"":[""[Period].[Month].&[2010-09]""]}]}";
var obj = JsonConvert.DeserializeObject<ReportSettings>(json_string);
When a json string contains an array of some json objects, we don't always need to defined the class using List<Type>. We can also define the class using array. The same json string will be able to create an object of the below class containing array instead of List.
public class ReportSettings
{
public class SelectedItems
{
public string level;
public string[] items;
}
public string[] row_elements;
public string[] column_elements;
public string[] filter_elements;
public string[] measure_elements;
public SelectedItems[] selected_items;
}
