C# Meets JSON: Lightweight Data-Interchange Format Explained

JSON

JavaScript Object Notation (JSON) is an open and lightweight data-interchange format easily readable by humans that consists of attribute-value pairs. Even though it is derived from JavaScript, it is totally language independent and the vast majority of modern programming languages have adopted it as an alternative to XML.

Nowadays, it is commonly used to transfer the data using the wire, usually between the server and the web application. Compared to XML, the code generation and parsing is much faster and simpler. Still, that doesn't mean that XML should be buried and sent to the dustbin of history as there are many scenarios when XML is a very viable option.

JSON Structure

JSON is built on the following two data structures:

  • An object that is a collection of name/value pairs
  • An array representing an ordered list of values

Object

An object is simply an unordered list of name/value pairs surrounded by curly brackets "{}". Each name/value pair is divided by a colon ":" and the name/value pairs are separated by a comma "," from each other.

 
Image 01: JSON object representation 
  1. {   
  2. "name" : "Mike",  
  3. "age" : 32,  
  4. "occupation" : "developer"  
  5. }  

Array

An array is an ordered list of values surrounded by square brackets "[]" with values themselves being separated by a comma ",".

 
Image 02: JSON object representation 
  1. [  
  2. "Austria",  
  3. "Germany",  
  4. "Slovakia"  
  5. ]  
Value

A value is one of the data representations listed below. These can be nested to create a complex multi-tier data structure.
 
 
 
 Image 03: JSON values
Advantages

  • Smaller in size than corresponding XML
  • Easier and faster parsing
  • Self-describing
  • Trivial to use with Ajax


  • Disadvantages

  • Does not allow any form of comment syntax
  • Doesn't support namespaces and schemas
  • Might be difficult to understand by humans
  • Not suitable for handling multimedia formats

  • JSON and C#

    When it comes to using JSON within our C# application, we have two options. The first one is to rely on the .Net built-in support and use the JavaScriptSerializer class from the System.Web.Extensions assembly or the DataContractJsonSerializer (available since .Net 3.5) class built and designed for WFC. The next option is to rely on some third-party library and add a reference to it. We ususally lean towards the built-in support whenever possible. However, in the case of JSON, using third-party libraries is much more popular.

    We will not be different and will use the most popular one called Json.NET with over 3 millions downloads and counting.

    Installing Json.NET

    We start by downloading the library and referencing it in our project. The times of boring downloads outside the Visual Studio are already forgotten and we can easily use the NuGet Package Manager (Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution). After invoking the manager from the menu, a window will pop-up with all the packages available.

    We use the search feature and type “json” into the textbox in the upper-right corner. After a short while, the list is populated with all the JSON related libraries. We choose "Json.NET" and hit the Install button.

     
    Image 04: NuGet Package Manager 
     
    After the installation process is over, we can visually verify that the reference was really added.
     
     Image 05: Reference verification
     

    Now everything is set up and we are ready to use JSON in our application.

    Serialize JSON

    Before diving deeper into the serialization process, we will create a simple dummy class for the serialization. We name the class “Person” and add the three properties, a name as string, an age as integer and occupations as a list of strings. 
    1. public class Person  
    2. {  
    3.         public string Name { getset; }  
    4.         public int Age { getset; }  
    5.         public IList<string> Occupations { getset; }  
    6. }  

    Please note that Json.NET supports a wide range of attributes for decorating the entire class or the properties themselves, so you can alter the final result. To learn more about these attributes I suggest using the official documentation: Json.NET documentation.

    To serialize a newly created Person object, we just call the static SerializeObject method that does all the stuff needed and returns a serialized string representation of our Person object. When calling the method, we also add the optional second parameter to preserve the formatting for the console output purposes. 
    1. Person person = new Person  
    2. {  
    3.                 Age = 30,  
    4.                 Name = "Peter",  
    5.                 Occupations = new List<string>  
    6.                 {  
    7.                     "Developer",  
    8.                     "Engineer",  
    9.                     "DB specialist"  
    10.                 }  
    11. };  
    12.   
    13. string json = JsonConvert.SerializeObject(person, Formatting.Indented);  
    14. Console.WriteLine(json);  

    Now we print the serialized string to the console to visually verify the process.

     
    Image 06: object serialization 

    Deserialize JSON

    For deserialization, we call the static DeserializeObject method that deserializes JSON to a specific .Net type. In this case, it is the Person type we have created. The method takes just one mandatory parameter, the serialized object in the form of a string.

    1. Person person2 = JsonConvert.DeserializeObject<Person>(json);  
    2. Console.WriteLine("Name: " + person2.Name);  
    3. Console.WriteLine("Age: " + person2.Age);  

    To verify the process, we print the Person's name and age to the console.

     
    Image 07: object deserialization 

    JSON.NET Advanced Topics

    Json.Net is a powerful and open-source library that offers much more than just pure object serialization and deserialization.

    It supports the JSON schema standard that is used to validate the structure via the Newtonsoft.Json.Schema namespace, very similar to XML Schema for XML. It also offers a LINQ to JSON API that enables quick querying and creation of JSON objects. To learn more about these advances topics, I suggest visiting the library's official website.

    Conclusion

    JSON is a lightweight and widely used data-exchange format that offers several benefits over the standard XML. In C#, we use either the built-in functionality to parse and serialize the object, or rely on some third-party library with Json.NET being the most popular


    Similar Articles