| by Arround The Web | No comments

How to Convert C# Objects to JSON and Vice Versa

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 the 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 a C# JSON to 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 this 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. Using the techniques that you learned in this post, you can port them to handle a more complex data such as nested arrays, etc. Feel free to reference the documentation for any missing pieces or clarification.

Share Button

Source: linuxhint.com

Leave a Reply