Wednesday, March 21, 2018

Deserialize / Serialize JSON using Newtonsoft.Json


Using Newtonsoft.Json its quiet easy to Deserialize / Serialize JSON. Below code snippet will show you how to do this. 

public partial class Window1 : Window
{
        public Window1()
        {
            InitializeComponent();
        }

        public class Product
        {
            public string Code { get; set; }
            public string Description { get; set; }
            public  List<Price> Price { get; set; }
        }
        public class Price
        {
            public decimal WholeSale { get; set; }
            public decimal Retail { get; set; }
        }
        public void Deserialize()
        {
            string json = @"[{'Code': 'P1','Description': 'Product1','Price' : [{'WholeSale':'11','Retail':'22'}]}
                            ,{'Code': 'P2','Description': 'Product2','Price' : [{'WholeSale':'33','Retail':'44'}]}
                            ]";
            var products = JsonConvert.DeserializeObject<List<Product>>(json);
        }
        public void Serialize()
        {
            var products = new List<Product>
            {
                new Product()
                {
                    Code = "P1",
                    Description = "Prodict1",
                    Price = new List<Price>()
                    {
                        new Price
                        {
                            Retail = 11,
                            WholeSale = 22
                        },
                    }
                },
                new Product()
                {
                    Code = "P2",
                    Description = "Prodict2",
                    Price = new List<Price>()
                    {
                        new Price
                        {
                            Retail = 33,
                            WholeSale = 44
                        },
                    }
                }
            };
            string json= JsonConvert.SerializeObject(products);
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Deserialize();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Serialize();
        }
}