Convert object to json and json to object in C#

In this article we will see how to convert an object to json string or how to convert a json string to an object in C#, we will try to write a generic class with two methods, one for converting an object to json and other for converting json string to an object.

I searched internet to get if there is anything like this with .net but could not found any which we can use directly, so let's write a generic class JSonHelper with two methods ConvertObjectToJSon and ConvertJSonToObject.

Add reference for System.Runtime.Serialization in your application

using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
public class JSonHelper 
{         
   public string ConvertObjectToJSon<T>(T obj)
   {
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
      MemoryStream ms = new MemoryStream();
      ser.WriteObject(ms, obj);
      string jsonString = Encoding.UTF8.GetString(ms.ToArray());
      ms.Close();
      return jsonString;
  }  

  public T ConvertJSonToObject<T>(string jsonString)
  {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
      MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
      T obj = (T)serializer.ReadObject(ms);
      return obj;
   }
}

That's it, we can use this class to convert any object to json string and any json string to object. Let's check by creating a Product class

public class Product
{
    public Int32 ProductID { get; set; }
    public String ProductName { get; set; }
    public String Category { get; set; }
    public Double Price { get; set; }
}

We will create an object of product and initialize it and then convert it into json

Product product = new Product();
product.ProductID = 1001;
product.ProductName="Samsung Galaxy III";
product.Category = "Mobile";
product.Price = 799.00;

JSonHelper helper = new JSonHelper();
String jsonResult = helper.ConvertObjectToJSon(product);

And here is the result:

{"Category":"Mobile","Price":799,"ProductID":1001,"ProductName":"Samsung Galaxy III"}

Now we will see how to convert our above json string to object, so see this

 JSonHelper helper = new JSonHelper();
 Product product = helper.ConvertJSonToObject<Product>(jsonResult);

Up to this we check with a normal object, Is our code able to convert a list of object to a json string and vise vers, let's see this in action

List<Product> products = new List<Product>();
Product product;
for (int i = 1; i <= 3; i++)
{
    product = new Product();
    product.ProductID = 1001;
    product.ProductName = String.Format("Samsung Galaxy {0}", i);
    product.Category = String.Format("Mobile {0}", i);
    product.Price = 10.00 * 1;
    products.Add(product);
}

JSonHelper helper = new JSonHelper();
String jsonResult = helper.ConvertObjectToJSon(products);
// Convert the sting to object
products = null;
products = helper.ConvertJSonToObject<List<Product>>(jsonResult);

And here is the output, so it is working smooth with List of type as well

[ { "Category" : "Mobile",
    "Price" : 10,
    "ProductID" : 1001,
    "ProductName" : "Samsung Galaxy 1"
  },
  { "Category" : "Mobile",
    "Price" : 10,
    "ProductID" : 1001,
    "ProductName" : "Samsung Galaxy 2"
  },
  { "Category" : "Mobile",
    "Price" : 10,
    "ProductID" : 1001,
    "ProductName" : "Samsung Galaxy 3"
  }
]

We saw it is working for List, can we say this code will work for an object which is a list of two other types? We will see this with example, so create class order and OrderLineItem and finally use these classes to create another class having list of Order and List of OrderLineItem

public class Order
{
    public Int32 OrderID { get; set; }
    public Decimal TotalAmount { get; set; }
}
public class OrderLineItem
{
    public Int32 OrderLineItemID { get; set; }
    public Int32 OrderID { get; set; }
    public String Product { get; set; }  
    public Int32 Quantity { get; set; }      
    public Decimal Price { get; set; }      
    public Decimal TotalAmount { get; set; }
}

public class OrderDetail
{
    public List<Order> order = new List<Order>();
    public List<OrderLineItem> orderLineItem = new List<OrderLineItem>();        
}

Now we will see how to our code is converting and whether creating correct json or not so see this:

OrderDetail orderDetail = new OrderDetail();
Order order;
OrderLineItem item;
Decimal OrderTotalAmount = 0;
for (int i = 1; i <= 2; i++)
{
  order = new Order();
  order.OrderID = 100 * i;
  for(int j=1; j<=3; j++)
  {
    item = new OrderLineItem();
    item.OrderLineItemID = i;
    item.OrderID = order.OrderID;
    item.Product = String.Format("Product {0}", j);
    item.Quantity = i*j;
    item.Price = 10 * i;
    item.TotalAmount = item.Price * item.Quantity;
    orderDetail.orderLineItem.Add(item);
    OrderTotalAmount += item.TotalAmount;
  } 
  order.TotalAmount = OrderTotalAmount;
  orderDetail.order.Add(order);
}

JSonHelper helper = new JSonHelper();
String jsonResult = helper.ConvertObjectToJSon(orderDetail);
// Now  try to convert our above json string to object.
orderDetail = null;
orderDetail = helper.ConvertJSonToObject<OrderDetail>(jsonResult);

And here is the output:

{ "order" : [ { "OrderID" : 100,
        "TotalAmount" : 60
      },
      { "OrderID" : 200,
        "TotalAmount" : 300
      }
    ],
  "orderLineItem" : [ { "OrderID" : 100,
        "OrderLineItemID" : 1,
        "Price" : 10,
        "Product" : "Product 1",
        "Quantity" : 1,
        "TotalAmount" : 10
      },
      { "OrderID" : 100,
        "OrderLineItemID" : 1,
        "Price" : 10,
        "Product" : "Product 2",
        "Quantity" : 2,
        "TotalAmount" : 20
      },
      { "OrderID" : 100,
        "OrderLineItemID" : 1,
        "Price" : 10,
        "Product" : "Product 3",
        "Quantity" : 3,
        "TotalAmount" : 30
      },
      { "OrderID" : 200,
        "OrderLineItemID" : 2,
        "Price" : 20,
        "Product" : "Product 1",
        "Quantity" : 2,
        "TotalAmount" : 40
      },
      { "OrderID" : 200,
        "OrderLineItemID" : 2,
        "Price" : 20,
        "Product" : "Product 2",
        "Quantity" : 4,
        "TotalAmount" : 80
      },
      { "OrderID" : 200,
        "OrderLineItemID" : 2,
        "Price" : 20,
        "Product" : "Product 3",
        "Quantity" : 6,
        "TotalAmount" : 120
      }
    ]
}

We see here our code is working in every situation.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • json
  • c#
  • asp.net
By Ali Adravi On 16 Jun, 13  Viewed: 27,316

Other blogs you may like

Convert datatable to json in C#

To convert a DataTable into JSON in C# is really very easy. Is there any class or method in .Net which can help us to directly do it, then answer is No. We need to write a small utility class or method which can help to convert any datatable into json easily.What we are going to do is, create a... By Ali Adravi   On 09 Jun 2013  Viewed: 19,109

Convert xml, json to class in asp.net c# by one click

Convert XML or JSON into a class by using visual studio is as easy as just copy and two clicks, never matter how big or how complicated is our XML or JSON. In this article we will create some dummy XML and json and will try to convert them into class without writing a single property manually. It... By Ali Adravi   On 20 Dec 2014  Viewed: 693

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 4,639

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 1,263

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 2,220