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
usingSystem.IO;usingSystem.Text;usingSystem.Runtime.Serialization.Json;publicclassJSonHelper{publicstringConvertObjectToJSon(T obj){DataContractJsonSerializerser=newDataContractJsonSerializer(typeof(T));MemoryStreamms=newMemoryStream();ser.WriteObject(ms,obj);stringjsonString=Encoding.UTF8.GetString(ms.ToArray());ms.Close();returnjsonString;}publicTConvertJSonToObject(stringjsonString){DataContractJsonSerializerserializer=newDataContractJsonSerializer(typeof(T));MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(jsonString));T obj=(T)serializer.ReadObject(ms);returnobj;}}
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
publicclassProduct{publicInt32ProductID{get;set;}publicStringProductName{get;set;}publicStringCategory{get;set;}publicDoublePrice{get;set;}}
We will create an object of product and initialize it and then convert it into json
Productproduct=newProduct();product.ProductID=1001;product.ProductName="Samsung Galaxy III";product.Category="Mobile";product.Price=799.00;JSonHelperhelper=newJSonHelper();StringjsonResult=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
JSonHelperhelper=newJSonHelper();Productproduct=helper.ConvertJSonToObject(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
Listproducts=newList();Productproduct;for(inti=1;i<=3;i++){product=newProduct();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);}JSonHelperhelper=newJSonHelper();StringjsonResult=helper.ConvertObjectToJSon(products);// Convert the sting to objectproducts=null;products=helper.ConvertJSonToObject>(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
publicclassOrder{publicInt32OrderID{get;set;}publicDecimalTotalAmount{get;set;}}publicclassOrderLineItem{publicInt32OrderLineItemID{get;set;}publicInt32OrderID{get;set;}publicStringProduct{get;set;}publicInt32Quantity{get;set;}publicDecimalPrice{get;set;}publicDecimalTotalAmount{get;set;}}publicclassOrderDetail{publicListorder=newList();publicListorderLineItem=newList();}
Now we will see how to our code is converting and whether creating correct json or not so see this:
OrderDetailorderDetail=newOrderDetail();Orderorder;OrderLineItemitem;DecimalOrderTotalAmount=0;for(inti=1;i<=2;i++){order=newOrder();order.OrderID=100*i;for(intj=1;j<=3;j++){item=newOrderLineItem();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);}JSonHelperhelper=newJSonHelper();StringjsonResult=helper.ConvertObjectToJSon(orderDetail);// Now try to convert our above json string to object.orderDetail=null;orderDetail=helper.ConvertJSonToObject(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.