Introduction
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is language independent, easy to understand and self-describing. It is use 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 are supply data from client size to server side in JSON string format so it is necessary to cast our JSON string to 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 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 want convert to and from 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.
- static void Main(string[] args)
- {
- stringjsonData = @ "{
- 'FirstName': 'Jignesh', 'LastName': 'Trivedi'
- }
- ";
- var myDetails = JsonConvert.DeserializeObject < MyDetail > (jsonData);
- Console.WriteLine(string.Concat("Hi ", myDetails.FirstName, " " + myDetails.LastName));
- Console.ReadLine();
- }
- public class MyDetail
- {
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- }
- Using JObject.Parse
JObject class has parse method, it parse the JSON string and converted into Key-value dictionary object. In following example, I have use “JObject.Parse” method and retrieve data using key.
- string jsonData = @"{
- 'FirstName':'Jignesh',
- 'LastName':'Trivedi'
- }";
-
- var details = JObject.Parse(jsonData);
- Console.WriteLine(string.Concat("Hi ", details["FirstName"], " " + details["LastName"]));
-
- Console.ReadLine();
In following code snippet, we just assign JObject.Parse method output to dynamic object and accessing value as properties of dynamic object.
- string jsonData = @"{
- 'FirstName':'Jignesh',
- 'LastName':'Trivedi'
- }";
- dynamic data = JObject.Parse(jsonData);
-
- Console.WriteLine(string.Concat("Hi ", data.FirstName, " " + data.LastName));
- Console.ReadLine();
Note that in above describe method property name or key name is case sensitive i.e. property name of class must match key of JSON data.
- Using Data Contract Json Serializer class
.NET framework has also provided classes for serializing and de-serializing to JSON. One of them is DataContractJsonSerializer. Using following code we can de-serialize the JSON object.
To use this method following points must be remembered,
• Project must have reference System.Runtime.Serialization library
• Class must decorate with DataContract and properties decorate with DataMember attributes
• Use WriteObject method for serialize an object and use ReadObject method for deserialize a JSON object.
- static void Main(string[] args)
- {
- string jsonData = "{ \"FirstName\":\"Jignesh\",\"LastName\":\"Trivedi\" }";
- DataContractJsonSerializerjsonSerializer = newDataContractJsonSerializer(typeof(MyDetail));
- MemoryStream stream = newMemoryStream(Encoding.UTF8.GetBytes(jsonData));
- stream.Position = 0;
- MyDetaildataContractDetail = (MyDetail) jsonSerializer.ReadObject(stream);
- Console.WriteLine(string.Concat("Hi ", dataContractDetail.FirstName, " " + dataContractDetail.LastName));
- Console.ReadLine();
- }
- [DataContract]
- public class MyDetail
- {
- [DataMember]
- public string FirstName {
- get;
- set;
- }
- [DataMember]
- public string LastName {
- get;
- set;
- }
- }
Output
Summary
Using the above described method we can parse JSON in C# code and extract value from this object.
Read more articles on JSON: