JSON Serialization and Deserialization in C#

Introduction

JSON serialization (converting C# objects to JSON) and deserialization (converting JSON to C# objects) is are common task in C# development, especially when dealing with data interchange between different systems or storing data in a human-readable format. In C#, this functionality is often handled using libraries such as Newtonsoft.Json (Json.NET) or the built-in System.Text.Json in more recent versions of .NET.

JSON Serialization (C# object to JSON)

Using Newtonsoft.Json (Json.NET)

Install Json.NET package

Install-Package Newtonsoft.Json

Serialize C# Object to JSON

using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };

        string json = JsonConvert.SerializeObject(person);

        Console.WriteLine(json);
        // Output: {"Name":"Alice","Age":30}
    }
}

Using System.Text.Json (Starting from .NET 5)

using System;
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Bob", Age = 25 };

        string json = JsonSerializer.Serialize(person);

        Console.WriteLine(json);
        // Output: {"Name":"Bob","Age":25}
    }
}

JSON Deserialization (JSON to C# object)

Using Newtonsoft.Json (Json.NET)

using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        string json = "{\"Name\":\"Alice\",\"Age\":30}";

        Person person = JsonConvert.DeserializeObject<Person>(json);

        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        // Output: Name: Alice, Age: 30
    }
}

Using System.Text.Json (Starting from .NET 5)

using System;
using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        string json = "{\"Name\":\"Bob\",\"Age\":25}";

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

        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        // Output: Name: Bob, Age: 25
    }
}

These examples demonstrate how to serialize C# objects to JSON and deserialize JSON into C# objects using Newtonsoft.Json (Json.NET) and System.Text.Json libraries. Choose the appropriate library based on your project requirements and framework version.

Up Next
    Ebook Download
    View all
    Diving Into OOP
    Read by 16.1k people
    Download Now!
    Learn
    View all