c sharp

How to Convert JSON to C# Class

JSON or JavaScript Object Notation is based on a subset of the JavaScript programming language, but it is language-independent and can be used with any programming language that has a JSON parser. To use JSON data in C# programming, one needs to convert JSON to a C# class. This makes it possible for programmers to interact with the data in a type-safe way, which reduces the risk of mistakes and makes the code simpler to maintain.

Working with JSON data in C# frequently necessitates converting the JSON data into C# classes that can be readily edited and used in the application. This tutorial will go over the process of converting JSON data to C# classes, with code examples to help you along the way.

How to Convert a JSON to a C# Class

The steps to convert a JSON to a C# Class are:

Step 1: Analyze the JSON data

The first step in converting JSON to a C# class is to analyze the JSON data and determine its structure. This involves identifying the keys or properties of the data and their corresponding data types. Once this information is gathered, we can begin to create a corresponding C# class that will represent the JSON data.

Step 2: Create a C# class that represents the JSON data

The JSON data’s name is then used to define a class. Inside this class, we define properties that match the keys in the JSON data. We set the data types of the properties to match the data types of the values in the JSON data. For example, if a key in the JSON data has a value of a string, we define the corresponding property in the C# class as a string.

Step 3: Deserialize the JSON data

After creating the C# class, the next step is to deserialize the JSON data into a class instance. This is possible with the Newtonsoft.Json library, which provides a straightforward API for deserializing JSON data. You need to install and import the Newtonsoft.Json package in order to use it in your code. Create an instance of the JsonSerializer class and call the Deserialize method, handing in the JSON data as a string and the C# class as the generic type parameter:

using Newtonsoft.Json;

// JSON data
string json = "{"name":"John Smith","age":30}";
// C# class
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
// Deserialize JSON data into a Person object
Person person = JsonConvert.DeserializeObject<Person>(json);

 

The JSON data in this example is a simple object with a name and age property, and the C# class is a Person class with similar properties. JsonConvert.DeserializeObject is used to convert JSON data into a Person object that can be edited and used in the application.

Step 4: Manipulate the C# object

After deserializing the JSON data into a C# object, it can be manipulated and used in the application as desired. Properties can be read or set, methods can be invoked, and the object can be provided as a parameter to other procedures or functions.

Here is an example of how to work with the Person object you made in the previous step:

// Get the person's name
string name = person.Name;

// Set the person'
s age
person.Age = 31;

// Call a method on the person object
person.PrintDetails();

 

The person object is used in this example to get the person’s name, set the person’s age, and call the PrintDetails method on the object.

Here is a complete code demonstrating how to convert JSON to a C# class.

using System;
using Newtonsoft.Json;

namespace JsonToClassExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{
                'firstName': 'Larry',
                'lastName': 'Kevin',
                'address': {
                    'street': 'Main Street',
                    'city': 'Venice',
                }
            }"
;

            Rootobject myObject = JsonConvert.DeserializeObject<Rootobject>(json);

            Console.WriteLine("The first name is: " + myObject.firstName);
            Console.WriteLine("The last name is: " + myObject.lastName);
            Console.WriteLine("The street is: " + myObject.address.street);
            Console.WriteLine("The city is: " + myObject.address.city);


            Console.ReadLine();
        }
    }

    public class Rootobject
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public Address address { get; set; }
    }

    public class Address
    {
        public string street { get; set; }
        public string city { get; set; }
    }
}

 

The above code demonstrates how to use Newtonsoft.Json NuGet package to deserialize a JSON string into a C# class. The JSON string comprises information on a person’s first and last name, as well as their address (street and city). As C# classes, the Rootobject and Address classes establish the structure of the JSON data.

The JsonConvert.DeserializeObject method is used to convert a JSON string into a Rootobject instance. The data is then displayed on the console by accessing the attributes of the Rootobject and Address classes. The Console.ReadLine method is used to halt the program before it terminates.

Output

Other Ways to Convert JSON to C#

You can also copy the JSON data to the clipboard and use a JSON to C# class generator to generate the C# class. There are several tools online, such as Json2CSharp and QuickType, that can help you generate your C# class from JSON data. Paste the JSON data in the appropriate field and let the tool generate the C# class for you. This approach is straightforward and quick. However, for learning purposes, you must follow the first method.

Conclusion

Converting JSON data to a C# class involves analyzing the JSON data, creating a corresponding C# class, and deserializing the JSON data into the C# class object. This process can be useful when working with JSON data in C# applications, making it easier to read, manipulate, and send data to web services or APIs. To swiftly translate JSON to C#, you may also utilize several web tools, such Json2CSharp and QuickType.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.