Working With JSON String In C#

Introduction

 
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.
    1. static void Main(string[] args)   
    2. {  
    3.     stringjsonData = @ "{  
    4.     'FirstName''Jignesh''LastName''Trivedi'  
    5. }  
    6. ";  
    7. var myDetails = JsonConvert.DeserializeObject < MyDetail > (jsonData);  
    8. Console.WriteLine(string.Concat("Hi ", myDetails.FirstName, " " + myDetails.LastName));  
    9. Console.ReadLine();  
    10. }  
    11. public class MyDetail  
    12. {  
    13.     public string FirstName {  
    14.         get;  
    15.         set;  
    16.     }  
    17.     public string LastName {  
    18.         get;  
    19.         set;  
    20.     }  
    21. }  
  • 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.
    1. string jsonData = @"{  
    2. 'FirstName':'Jignesh',  
    3. 'LastName':'Trivedi'  
    4. }";  
    5.   
    6. var details = JObject.Parse(jsonData);  
    7. Console.WriteLine(string.Concat("Hi ", details["FirstName"], " " + details["LastName"]));  
    8.   
    9. Console.ReadLine(); 
    In the following code snippet, we just assign JObject.Parse method output to dynamic object and access value as properties of dynamic object.
    1. string jsonData = @"{  
    2. 'FirstName':'Jignesh',  
    3. 'LastName':'Trivedi'  
    4. }";  
    5. dynamic data = JObject.Parse(jsonData);  
    6.   
    7. Console.WriteLine(string.Concat("Hi ", data.FirstName, " " + data.LastName));  
    8. Console.ReadLine();  
    Note that in the above-described 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

    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.
    1. static void Main(string[] args)  
    2. {  
    3.         string jsonData = "{ \"FirstName\":\"Jignesh\",\"LastName\":\"Trivedi\" }";  
    4.         DataContractJsonSerializerjsonSerializer = newDataContractJsonSerializer(typeof(MyDetail));  
    5.         MemoryStream stream = newMemoryStream(Encoding.UTF8.GetBytes(jsonData));  
    6.         stream.Position = 0;  
    7.         MyDetaildataContractDetail = (MyDetail) jsonSerializer.ReadObject(stream);  
    8.         Console.WriteLine(string.Concat("Hi ", dataContractDetail.FirstName, " " + dataContractDetail.LastName));  
    9.         Console.ReadLine();  
    10.     }  
    11.     [DataContract]  
    12. public class MyDetail  
    13. {  
    14.     [DataMember]  
    15.     public string FirstName {  
    16.         get;  
    17.         set;  
    18.     }  
    19.     [DataMember]  
    20.     public string LastName {  
    21.         get;  
    22.         set;  
    23.     }  
    24. }  
Output
 
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: