c sharp

How to Deserialize JSON to C# Objects

JavaScript Object Notation has been at the fore front of data interchange ever since its release. Whether you are making a basic query to an API or performing a complex data exchange between multiple layers of an application, you will find JSON sitting at the board.

The reason for this is extensibility. First off, JSON is extremely lightweight, human-readable, and very easy to parse with a wide array of application. This makes it an excellent choice even in embedded devices.

Like all programming languages, C# supports the functionality to work with JSON data from multiple sources. For this tutorial, however, we will focus on learning how to work with C# objects. This allows us to convert a C# object into JSON and vice versa.

What Is an Object in C#?

In C#, an object refers to an instance of a class or structure that is defined in the application. Think of classes as blueprints that define the properties, methods, and events that can be accessed by the methods.

Once we create an object from the class, also known as instantiation, the object encapsulates the data and behavior that are defined in the class.

An example of a class and object is as follows:

public class Car
{
    public string Model { get; set; }
    public int Mileage { get; set; }
}

// instantiation
Car car = new Car
{
    Model = "Benz",
    Mileage= 0
};
Console.WriteLine(car.Model);
Console.WriteLine(car.Mileage);

In the given example, we start by creating a new class called β€œCar” with two properties which define the model of the car and the mileage.

Next, we create a new object called β€œcar” from the β€œCar” class and pass the properties of the class.

Lastly, we access the methods of the object using the dot notation as shown in the previous example.

Convert a C# Object to JSON (Serialization)

Let us discuss how we can convert a C# object into JSON.

One of the most powerful and efficient method of converting an object into JSON is using the Netwonsoft package.

The β€œNewtonsoft.JSON” library is a powerful library that allows us to work with a JSON data in the β€œ.NET” ecosystem with ease.

We can start by installing it into our project by running the following command in the NuGet terminal.

Install-Package Newtonsoft.Json

This command should download and install the Newtownsoft.JSON package on the target project.

Once we install the library, we can use the JsonConvert.SerializeObject() to convert an object into a JSON string as demonstrated in the following example:

using Newtonsoft.Json;
using System;
public class Car
{
    public string Model { get; set; }
    public int Mileage { get; set; }
    public string Year { get; set; }
}
public class Program
{
    public static void Main()
    {
        Car car = new Car
        {
            Model = "Benz",
            Mileage = 2000,
            Year = "2016"
        };
        string jsonString = JsonConvert.SerializeObject(car);
        Console.WriteLine(jsonString);
    }
}

In the given example, we start by importing the required namespaces for our project. In our case, we need the system and Newtonsoft.JSON package.

Next, we proceed to create a β€œCar” class with the properties of Model, Mileage, and Year.

As you can guess, we instantiate a new object called β€œcar” with the values for the β€œproject” class.

Lastly, we use the JsonConvert.SerializeObject() to convert the car object into a JSON string and print it to the console.

The resulting output is as follows:

{"Model":"Benz","Mileage":2000,"Year":"2016"}

Convert JSON to a C# Object (Deserialization)

In other cases, you might need to convert a JSON string into a valid C# object. This is also known as deserialization.

Luckily, we can call the JsonConvert.DeserializeObject() method and pass the valid JSON string as the parameter to convert it into an object.

Take for example the following code demonstration:

using Newtonsoft.Json;
using System;

public class Car
{
    public string Model { get; set; }
    public int Mileage { get; set; }
    public string Year { get; set; }
}

public class Program
{
    public static void Main()
    {
        string jsonString = "{"Model":"Benz","Mileage":2000,"Year":"2023"}";
        Car car = JsonConvert.DeserializeObject<Car>(jsonString);
        Console.WriteLine($"Model: {car.Model}, Mileage: {car.Mileage}, Year: {car.Year}");
    }
}

In the given example, we use the JsonConvert.DeserialzeObject() to convert a JSON string into the β€œCar” object.

NOTE: In the previous example, we include the escape sequences to escape the double quotes which are part of the data.

Once converted, we can then access the properties of the object like we would do with any normal C# object.

Output:

Model: Benz, Mileage: 2000, Year: 2023

Conclusion

In this tutorial, we walked you through the steps and methods that we can use to convert a C# object into a JSON string and vice versa.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list