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.