Tuesday 7 January 2020

Converting 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
  1. using System.IO;
  2. using System.Text;
  3. using System.Runtime.Serialization.Json;
  4. public class JSonHelper
  5. {        
  6.    public string ConvertObjectToJSon<T>(T obj)
  7.    {
  8.       DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  9.       MemoryStream ms = new MemoryStream();
  10.       ser.WriteObject(ms, obj);
  11.       string jsonString = Encoding.UTF8.GetString(ms.ToArray());
  12.       ms.Close();
  13.       return jsonString;
  14.   }  
  15.   public T ConvertJSonToObject<T>(string jsonString)
  16.   {
  17.       DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  18.       MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  19.       T obj = (T)serializer.ReadObject(ms);
  20.       return obj;
  21.    }
  22. }
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
  1. public class Product
  2. {
  3.     public Int32 ProductID { get; set; }
  4.     public String ProductName { get; set; }
  5.     public String Category { get; set; }
  6.     public Double Price { get; set; }
  7. }
We will create an object of product and initialize it and then convert it into json
  1. Product product = new Product();
  2. product.ProductID = 1001;
  3. product.ProductName="Samsung Galaxy III";
  4. product.Category = "Mobile";
  5. product.Price = 799.00;
  6. JSonHelper helper = new JSonHelper();
  7. 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
  1. List<Product> products = new List<Product>();
  2. Product product;
  3. for (int i = 1; i <= 3; i++)
  4. {
  5.     product = new Product();
  6.     product.ProductID = 1001;
  7.     product.ProductName = String.Format("Samsung Galaxy {0}", i);
  8.     product.Category = String.Format("Mobile {0}", i);
  9.     product.Price = 10.00 * 1;
  10.     products.Add(product);
  11. }
  12. JSonHelper helper = new JSonHelper();
  13. String jsonResult = helper.ConvertObjectToJSon(products);
  14. // Convert the sting to object
  15. products = null;
  16. products = helper.ConvertJSonToObject<List<Product>>(jsonResult);
And here is the output, so it is working smooth with List of type as well
  1. [ { "Category" : "Mobile",
  2.     "Price" : 10,
  3.     "ProductID" : 1001,
  4.     "ProductName" : "Samsung Galaxy 1"
  5.   },
  6.   { "Category" : "Mobile",
  7.     "Price" : 10,
  8.     "ProductID" : 1001,
  9.     "ProductName" : "Samsung Galaxy 2"
  10.   },
  11.   { "Category" : "Mobile",
  12.     "Price" : 10,
  13.     "ProductID" : 1001,
  14.     "ProductName" : "Samsung Galaxy 3"
  15.   }
  16. ]
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
  1. public class Order
  2. {
  3.     public Int32 OrderID { get; set; }
  4.     public Decimal TotalAmount { get; set; }
  5. }
  6. public class OrderLineItem
  7. {
  8.     public Int32 OrderLineItemID { get; set; }
  9.     public Int32 OrderID { get; set; }
  10.     public String Product { get; set; }  
  11.     public Int32 Quantity { get; set; }      
  12.     public Decimal Price { get; set; }      
  13.     public Decimal TotalAmount { get; set; }
  14. }
  15. public class OrderDetail
  16. {
  17.     public List<Order> order = new List<Order>();
  18.     public List<OrderLineItem> orderLineItem = new List<OrderLineItem>();        
  19. }
Now we will see how to our code is converting and whether creating correct json or not so see this:
  1. OrderDetail orderDetail = new OrderDetail();
  2. Order order;
  3. OrderLineItem item;
  4. Decimal OrderTotalAmount = 0;
  5. for (int i = 1; i <= 2; i++)
  6. {
  7.   order = new Order();
  8.   order.OrderID = 100 * i;
  9.   for(int j=1; j<=3; j++)
  10.   {
  11.     item = new OrderLineItem();
  12.     item.OrderLineItemID = i;
  13.     item.OrderID = order.OrderID;
  14.     item.Product = String.Format("Product {0}", j);
  15.     item.Quantity = i*j;
  16.     item.Price = 10 * i;
  17.     item.TotalAmount = item.Price * item.Quantity;
  18.     orderDetail.orderLineItem.Add(item);
  19.     OrderTotalAmount += item.TotalAmount;
  20.   }
  21.   order.TotalAmount = OrderTotalAmount;
  22.   orderDetail.order.Add(order);
  23. }
  24. JSonHelper helper = new JSonHelper();
  25. String jsonResult = helper.ConvertObjectToJSon(orderDetail);
  26. // Now  try to convert our above json string to object.
  27. orderDetail = null;
  28. orderDetail = helper.ConvertJSonToObject<OrderDetail>(jsonResult);
And here is the output:
  1. { "order" : [ { "OrderID" : 100,
  2.         "TotalAmount" : 60
  3.       },
  4.       { "OrderID" : 200,
  5.         "TotalAmount" : 300
  6.       }
  7.     ],
  8.   "orderLineItem" : [ { "OrderID" : 100,
  9.         "OrderLineItemID" : 1,
  10.         "Price" : 10,
  11.         "Product" : "Product 1",
  12.         "Quantity" : 1,
  13.         "TotalAmount" : 10
  14.       },
  15.       { "OrderID" : 100,
  16.         "OrderLineItemID" : 1,
  17.         "Price" : 10,
  18.         "Product" : "Product 2",
  19.         "Quantity" : 2,
  20.         "TotalAmount" : 20
  21.       },
  22.       { "OrderID" : 100,
  23.         "OrderLineItemID" : 1,
  24.         "Price" : 10,
  25.         "Product" : "Product 3",
  26.         "Quantity" : 3,
  27.         "TotalAmount" : 30
  28.       },
  29.       { "OrderID" : 200,
  30.         "OrderLineItemID" : 2,
  31.         "Price" : 20,
  32.         "Product" : "Product 1",
  33.         "Quantity" : 2,
  34.         "TotalAmount" : 40
  35.       },
  36.       { "OrderID" : 200,
  37.         "OrderLineItemID" : 2,
  38.         "Price" : 20,
  39.         "Product" : "Product 2",
  40.         "Quantity" : 4,
  41.         "TotalAmount" : 80
  42.       },
  43.       { "OrderID" : 200,
  44.         "OrderLineItemID" : 2,
  45.         "Price" : 20,
  46.         "Product" : "Product 3",
  47.         "Quantity" : 6,
  48.         "TotalAmount" : 120
  49.       }
  50.     ]
  51. }
We see here our code is working in every situation.

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...