C# JSON to Class - C# Class from JSON

JSON (JavaScript Object Notation) is now widely accepted as the standard for exchanging data over the internet.

Handling JSON data is an essential task in modern applications. Today, we will delve into the process of converting JSON to C# class and C# class to JSON. We will also offer code samples to aid in understanding the process better.

JSON is a data-interchange format that is easy for humans to read write and easy for machines to parse and generate. The structure of JSON is straightforward, with a key-value pair format.

C# classes, on the other hand, are a way to represent and define the structure of an object in the C#. Classes are a fundamental building block of C# programming and provide a blueprint for creating objects with specific properties and methods.

The relationship between JSON and C# classes lies in their ability to represent structured data. JSON can be easily serialized and deserialized to C# classes, allowing developers to manipulate data more effectively.

JSON to C# Class

One common task is to convert JSON data into a C# class. There are different ways to convert JSON to C# class, and two popular libraries for doing so are System.Text.Json and Newtonsoft.Json.

The System.Text.Json library is a part of the shared framework in .NET Runtime. If you need to use it in other frameworks, you have to install the package. All these libraries are available as Nuget packages.

Let's dive into code examples for C# deserialize json to class, using each library:

JSON Class C# - using Newtonsoft.Json

Using Newtonsoft.Json, JSON to C# class can be easily done using the JsonConvert.DeserializeObject<T> method.

Here are the steps:

  1. Install the Newtonsoft.Json NuGet package.
  2. Create a C# class that matches the JSON structure.
  3. Now use the JsonConvert.DeserializeObject<T> method to deserialize the JSON string into C# objects.
// Include namespace for Newtonsoft.Json NuGet package
using Newtonsoft.Json;

// JSON data
string jsonData = "{\"name\":\"John Doe\",\"age\":30,\"city\":\"New York\"}";

// C# class
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

// Deserialize JSON data into C# object
Person person = JsonConvert.DeserializeObject<Person>(jsonData);

C# JSON to class - using System.Text.Json

using System.Text.Json;

string json = @"{
                ""Name"": ""John Doe"",
                ""Age"": 30,
                ""Hobbies"": [""Reading"", ""Traveling""]
            }";


Person person = new Person
{
    Name = "John Doe",
    Age = 30,
    Hobbies = new List<string> { "Reading", "Traveling" }
};

Person person = JsonSerializer.Deserialize<Person>(json);

C# Class to JSON

Another common task is to convert the C# object to JSON data. To convert C# class to JSON, we can also use Newtonsoft.Json and System.Text.Json libraries. To do this, you can use the JsonConvert.SerializeObject method from the Newtonsoft.Json library.

Code example for Serialize Class to JSON C#:

// Include namespace for Newtonsoft.Json NuGet package
using Newtonsoft.Json;

// C# class
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

// C# object
Person person = new Person
{
    Name = "John Doe",
    Age = 30,
    City = "New York"
};

// Serialize C# object into JSON data
string jsonData = JsonConvert.SerializeObject(person);

C# class to JSON using System.Text.Json

using System.Text.Json;

Person person = new Person
{
    Name = "John Doe",
    Age = 30,
    Hobbies = new List<string> { "Reading", "Traveling" }
};

string json = JsonSerializer.Serialize(person);


Generate C# Class from JSON Schema

JSON schema is a vocabulary that allows us to define the structure of JSON data. It is essential for validating JSON data and ensuring that it adheres to a specific structure. Let’s learn to generate C# class from JSON schema.

Following example uses the NJsonSchema and NJsonSchema.CodeGeneration.CSharp NuGet packages to generate C# code from the given JSON schema.

using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;

string jsonSchema = @"{
    'type': 'object',
    'properties': {
        'Name': { 'type': 'string' },
        'Age': { 'type': 'integer' },
        'Hobbies': {
            'type': 'array',
            'items': { 'type': 'string' }
        }
    }
}";

JsonSchema schema = await JsonSchema.FromJsonAsync(jsonSchema);
CSharpGenerator generator = new CSharpGenerator(schema);
string csharpCode = generator.GenerateFile("Person");

Generate C# Class from JSON Schema online

Sometimes, the JSON data structure may be complex and it can be difficult to manually create the corresponding C# classes. In such cases, we can use online tools to generate C# class from JSON.

Here are some popular online tools that can generate c# class from JSON schema online:

  1. Json2CSharp : json2csharp.com
  2. Quicktype : app.quicktype.io
  3. JsonUtils : jsonutils.com

C# Generate JSON schema from class

Generating JSON schema from C# classes is crucial for ensuring that the serialized JSON data complies with the expected structure. You can use libraries like Newtonsoft.Json.Schema.

Cod example using Newtonsoft.Json.Schema:

using Newtonsoft.Json.Schema.Generation;
Person person = new Person
        {
            Name = "John Doe",
            Age = 30,
            Hobbies = new List<string> { "Reading", "Traveling" }
        };

        JSchemaGenerator generator = new JSchemaGenerator();
        var schema = generator.Generate(typeof(Person));
        string jsonSchema = schema.ToString();
        
        Console.WriteLine(jsonSchema);

C# class to JSON schema online

Similarly, we can also use online tools to generate JSON schema from C# classes. dotnetfiddle.net is one of the popular.

C# Create JSON object without class

To do this, we can use an anonymous object and the JsonConvert.SerializeObject method from the Newtonsoft.Json library to create a JSON object without a class.

Summary

In this article, we've covered the basics of JSON and C# classes, the different ways to convert JSON to C# class and C# class to JSON, as well as c# class to json schema and C# class from JSON schema. We've shown code examples using popular libraries like System.Text.Json and Newtonsoft.Json.Schema.

By mastering these concepts and techniques, you'll be able to effectively manage and manipulate data in your C# applications. For further learning, consider exploring the official documentation for the libraries mentioned in this article.