This post is about example for serialize and deserialize json data with C#. This example using Newtonsoft.Json to be a library to work with json data.
You can add Newtonsoft.Json by download from https://www.newtonsoft.com/json or using Nuget to add it into your project.
In this example is Bill object that hold billing data about Car object.
Serialize Object to String
Below is example code to serialize object to json string. At line 39 is code to convert object into json string with beautiful json format.
Output
Deerialize JSON string to object
Below is example to reverse json string to specific object.
Below is output after deserialized.
Download example code here.
You can add Newtonsoft.Json by download from https://www.newtonsoft.com/json or using Nuget to add it into your project.
In this example is Bill object that hold billing data about Car object.
Serialize Object to String
Below is example code to serialize object to json string. At line 39 is code to convert object into json string with beautiful json format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace JSON { class JSonExample { static void Main(string[] args) { List<Car> cars = new List<Car>(); float totalPrice = 0; Car car1 = new Car(); car1.brand = "Honda"; car1.color = "Bronze"; car1.price = 100; car1.id = 1; totalPrice = totalPrice + car1.price; Car car2 = new Car(); car2.brand = "Toyota"; car2.color = "Red"; car2.price = 90; car2.id = 1; totalPrice = totalPrice + car2.price; cars.Add(car1); cars.Add(car2); Bill bill = new Bill(); bill.billNo = "ABC123"; bill.cars = cars; bill.totalPrice = totalPrice; bill.address = new string[] { "Address1", "Address2"}; string json = JsonConvert.SerializeObject(bill, Formatting.Indented); Console.WriteLine(json); // Press any key to close window Console.ReadLine(); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | { "billNo": "ABC123", "cars": [ { "id": 1, "color": "Bronze", "brand": "Honda", "price": 100.0 }, { "id": 1, "color": "Red", "brand": "Toyota", "price": 90.0 } ], "totalPrice": 190.0, "address": [ "Address1", "Address2" ] } |
Deerialize JSON string to object
Below is example to reverse json string to specific object.
1 | Bill deserializedBill = JsonConvert.DeserializeObject<Bill>(json); |
Below is output after deserialized.
Download example code here.
Comments
Post a Comment