Introduction
What is JSON?
- Collection of name/value pairs – This Data Structure is supported by different programming languages.
- Ordered list of values – It includes array, list, vector or sequence etc.
JSON has following styles,
- Object
An unordered “name/value” assembly. An object begins with “{” and ends with “}”. Behind each “name”, there is a colon. And comma is used to separate much “name/value”. For example,- var user = {“name”:“Manas”,“gender”:“Male”,“birthday”:“1987-8-8”}
- Array
Value order set. An array begins with “[” and end with “]”. And values are separated with commas. For example,- var userlist = [{“user”:{“name”:“Manas”,“gender”:“Male”,“birthday”:“1987-8-8”}},
- {“user”:{“name”:“Mohapatra”,“Male”:“Female”,“birthday”:“1987-7-7”}}]
- String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.- var userlist = “{\”ID\”:1,\”Name\”:\”Manas\”,\”Address\”:\”India\”}”
- Using JavaScriptSerializer class
- Using DataContractJsonSerializer class
- Using JSON.NET library
Using DataContractJsonSerializer
Let’s say there is Employee class with properties such as name, address and property values also assigned. Now we can convert the Employee class instance to JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
- [DataContract]
- class BlogSite
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public string Description { get; set; }
- }
Serialization
- BlogSite bsObj = new BlogSite()
- {
- Name = “C-sharpcorner”,
- Description = “Share Knowledge”
- };
- DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
- MemoryStream msObj = new MemoryStream();
- js.WriteObject(msObj, bsObj);
- msObj.Position = 0;
- StreamReader sr = new StreamReader(msObj);
- // “{\”Description\”:\”Share Knowledge\”,\”Name\”:\”C-sharpcorner\”}”
- string json = sr.ReadToEnd();
- sr.Close();
- msObj.Close();
Deserialization
- string json = “{\”Description\”:\”Share Knowledge\”,\”Name\”:\”C-sharpcorner\”}”;
- using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
- {
- // Deserialization from JSON
- DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
- BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
- Response.Write(“Name: “ + bsObj2.Name); // Name: C-sharpcorner
- Response.Write(“Description: “ + bsObj2.Description); // Description: Share Knowledge
- }
Using JavaScriptJsonSerializer
- class BlogSites
- {
- public string Name { get; set; }
- public string Description { get; set; }
- }
Serialization
- // Creating BlogSites object
- BlogSites bsObj = new BlogSites()
- {
- Name = “C-sharpcorner”,
- Description = “Share Knowledge”
- };
- // Serializing object to json data
- JavaScriptSerializer js = new JavaScriptSerializer();
- string jsonData = js.Serialize(bsObj); // {“Name”:”C-sharpcorner”,”Description”:”Share Knowledge”}
Deserialization
- // Deserializing json data to object
- JavaScriptSerializer js = new JavaScriptSerializer();
- BlogSites blogObject = js.Deserialize(jsonData);
- string name = blogObject.Name;
- string description = blogObject.Description;
- // Other way to whithout help of BlogSites class
- dynamic blogObject = js.Deserialize(jsonData);
- string name = blogObject[“Name”];
- string description = blogObject[“Description”];
Using Json.NET
- Flexible JSON serializer for converting between .NET objects and JSON.
- LINQ to JSON for manually reading and writing JSON.
- High performance, faster than .NET’s built-in JSON serializers.
- Easy to read JSON.
- Convert JSON to and from XML.
- Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Serialization
- // Creating BlogSites object
- BlogSites bsObj = new BlogSites()
- {
- Name = “C-sharpcorner”,
- Description = “Share Knowledge”
- };
- // Convert BlogSites object to JOSN string format
- string jsonData = JsonConvert.SerializeObject(bsObj);
- Response.Write(jsonData);
Deserialization
- string json = @”{
- ‘Name’: ‘C-sharpcorner’,
- ‘Description’: ‘Share Knowledge’
- }”;
- BlogSites bsObj = JsonConvert.DeserializeObject(json);
- Response.Write(bsObj.Name);
Conclusion
In this article we discussed about how many ways we can implement serialization/deserialization in C#. However JSON.NET wins over other implementations because it facilitates more functionality of JSON validation, JSON schema, LINQ to JSON etc. So use JSON.NET always.
Hope you liked it…
Please Comments, Share & Subscribe.
THREE QUERIES offers easy access to information about SharePoint and associated technologies, project management, agile and scrum methodologies that helps developers, administrators, architects, technical managers, business analysts and end users. It has grown from there. We provide an important knowledge base for those involved in managing, architecture and developing software projects of all kinds. With weekly/daily exclusive updates, we keep you in touch with the latest business, management, technology thinking.
WE ARE CONNECTED ~ Follow us on social media to get regular updates and opinion on what's happening in the world of SharePoint, front-end, back end web technologies and project management. If you like this article, please share it and follow us at Facebook, Twitter, Instagram, Pinterest and LinkedIn