Header add

In this article we will learn about how to Extract data from JSON String In C#, JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is language-independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is very popular nowadays.

JSON represents objects in structured text format and data stored in key-value pairs. Many third-party controls like Kendo UI grid supply data from client size to server-side in JSON string format so it is necessary to cast our JSON string to the appropriate object to access data. There are many ways for working with JSON in C# code.

Using Newtonsoft Libraries

Newtonsoft is also known as Json.NET. It is a high-performance JSON framework for .NET. It is very easy to use and much faster than the built-in JSON serializes of .NET.

Using JsonConverter

JsonConvert class has a method to convert to and from JSON string, SerializeObject() and DeserializeObject() respectively. It can be used where we won't to convert to and from a JSON string.

In the following example, I have used "JsonConvert.DeserializeObject" method to cast my JSONobject to my custom class object. Here JSON key name must match with the class property name and matching is case insensitive.



Using JObject.Parse
 
JObject class has parse method; it parses the JSON string and converts it into a Key-value dictionary object. In the following example, I have used "JObject.Parse" method and retrieved data using key.

Using Data Contract Json Serializer class
 
The .NET framework has also provided classes for serializing and de-serializing to JSON. One of them is DataContractJsonSerializer. Using the following code we can deserialize the JSON object. To use this method the following points must be remembered,
  • The project must have a reference System.Runtime.Serialization library
  • The class must decorate with DataContract and properties decorate with DataMember attributes
  • Use WriteObject method for serializing an object and use ReadObject method for deserializing a JSON object.


Output

Post a Comment

Previous Post Next Post