How do I serialize and deserialize JSON data in C#?

JSON is a widely used data format for sharing data between applications. When working with .NET applications, it’s common to convert JSON data to .NET objects and vice versa. The process of converting .NET objects to JSON is called serialization, and the process of converting JSON to .NET objects is called deserialization. In this article, we’ll explore how to perform both serialization and deserialization of JSON data using C# through code examples.

What is JSON?

JSON stands for JavaScript Object Notation. It is a standard text-based format for representing structured data based on JavaScript object syntax1. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client so it can be displayed on a web page or vice versa)1. JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays (or other serializable values).

Here’s an example of a JSON object that represents a person:

{
    "firstName": "John",
    "lastName": "Doe",
    "age": 25,
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "state": "IL",
        "zip": "12345"
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "555-555-1234"
        },
        {
            "type": "work",
            "number": "555-555-5678"
        }
    ]
}

This JSON object has several key-value pairs. The values can be strings, numbers, objects, or arrays. In this example, the address key has an object as its value, and the phoneNumbers key has an array of objects as its value.

JSON object vs array vs string

In JSON, object, array, and string are three different components and structures within the JSON format. Here's a breakdown of the differences between them:

JSON Object: A JSON object is an unordered collection of key-value pairs enclosed in curly braces {}. Each key is a string, followed by a colon :, and then the corresponding value. JSON objects represent complex data structures and are often used to organize and represent entities or entities' properties.

Example:

{
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

In this example, the entire structure enclosed in curly braces {} represents a JSON object. The keys "name", "age", and "email" are strings, and their corresponding values are "John Doe", 30, and "[email protected]", respectively.

JSON Array: A JSON array is an ordered collection of values enclosed in square brackets []. Values within a JSON array can be of any data type, such as strings, numbers, booleans, objects, or even other arrays. JSON arrays are useful for representing and working with lists or collections of related data.

Example:

[
  "apple",
  "banana",
  "orange"
]

In this example, the structure enclosed in square brackets [] represents a JSON array. It contains three JSON strings: "apple", "banana", and "orange", which are the values within the array.
JSON String: A JSON string is a sequence of characters surrounded by double quotation marks " within a JSON structure. JSON strings are used to represent textual data and are typically associated with keys in JSON objects or as values within JSON arrays.

Example:

"Hello, World!"

In this example, "Hello, World!" represents a JSON string, as it is enclosed in double quotation marks.

To summarize, a JSON object is a collection of key-value pairs enclosed in curly braces, a JSON array is an ordered collection of values enclosed in square brackets, and a JSON string is a textual data enclosed in double quotation marks. These structures serve different purposes in organizing and representing data within the JSON format.

Serialization and Deserialization in .NET

In .NET, serialization refers to the process of converting an object into a format that can be easily stored, transmitted, or reconstructed later. It is a fundamental concept in software development when working with objects that need to be persisted, transferred over a network, or shared between different applications.

Serialization allows you to convert objects into a stream of bytes or a textual representation that can be saved to a file, sent over a network, or stored in a database. This process is useful when you want to preserve the state of an object or transfer it between different layers of an application or across different machines.

.NET provides built-in support for serialization through the serialization framework, which is part of the Common Language Runtime (CLR). This framework allows you to serialize objects by using different serialization techniques such as binary serialization, XML serialization, or JSON serialization.

Binary serialization is the process of converting an object into a binary format. It is suitable for scenarios where the serialized data needs to be compact and efficient. The resulting binary data can be saved to a file or transmitted over a network.

XML serialization converts objects into an XML representation. This format is human-readable and can be easily processed by other applications or platforms that understand XML. XML serialization is often used when interoperability with other systems is required.

JSON serialization, similar to XML serialization, converts objects into a textual representation. JSON (JavaScript Object Notation) is a lightweight and widely supported format, making it a popular choice for web-based applications and services.

To make an object serializable in .NET, you can mark it with the [Serializable] attribute, which indicates that the object's state can be serialized. Additionally, you may need to mark specific fields or properties with attributes such as [NonSerialized] to exclude them from serialization if necessary.

The process of deserialization is the reverse of serialization, where the serialized data is converted back into an object. By deserializing the data, you can reconstruct the original object with its previous state.

Serialize JSON in C#

The process of converting .NET objects into JSON strings is called serialization. In C#, you can use the JsonSerializer.Serialize method to convert a .NET object to a JSON string. Here’s an example that shows how to store the above JSON data into a string in C#:

using System;
using System.Text.Json;

namespace Example
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public Address Address { get; set; }
        public PhoneNumber[] PhoneNumbers { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }

    public class PhoneNumber
    {
        public string Type { get; set; }
        public string Number { get; set; }
    }

    public static void Main()
    {
        var person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Age = 25,
            Address = new Address
            {
                Street = "123 Main St",
                City = "Springfield",
                State = "IL",
                Zip = "12345"
            },
            PhoneNumbers = new PhoneNumber[]
            {
                new PhoneNumber
                {
                    Type = "home",
                    Number = "555-555-1234"
                },
                new PhoneNumber
                {
                    Type = "work",
                    Number = "555-555-5678"
                }
            }
        };

        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
    }
}

This code defines classes for Person, Address, and PhoneNumber that match the structure of the JSON data. It then creates an instance of the Person class and populates it with data. Finally, it uses the JsonSerializer.Serialize method to convert the Person object to a JSON string.

The output of the above program would be a JSON string representation of the Person object that was created in the code. The output would look like this:

{"FirstName":"John","LastName":"Doe","Age":25,"Address":{"Street":"123 Main St","City":"Springfield","State":"IL","Zip":"12345"},"PhoneNumbers":[{"Type":"home","Number":"555-555-1234"},{"Type":"work","Number":"555-555-5678"}]}

This is the same data that was used to create the Person object, but now it is represented as a JSON string.

Deserialize JSON in C#

In C#, you can use the JsonSerializer.Deserialize method to parse a JSON string and convert it into a .NET object. Here’s an example that shows how to parse the above JSON string and convert it into a Person object:

using System;
using System.Text.Json;

namespace Example
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public Address Address { get; set; }
        public PhoneNumber[] PhoneNumbers { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }

    public class PhoneNumber
    {
        public string Type { get; set; }
        public string Number { get; set; }
    }

    public static void Main()
    {
        string jsonString = "{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":25,\"Address\":{\"Street\":\"123 Main St\",\"City\":\"Springfield\",\"State\":\"IL\",\"Zip\":\"12345\"},\"PhoneNumbers\":[{\"Type\":\"home\",\"Number\":\"555-555-1234\"},{\"Type\":\"work\",\"Number\":\"555-555-5678\"}]}";
        
        Person person = JsonSerializer.Deserialize<Person>(jsonString);
        
        Console.WriteLine($"First Name: {person.FirstName}");
        Console.WriteLine($"Last Name: {person.LastName}");
        Console.WriteLine($"Age: {person.Age}");
        Console.WriteLine($"Address: {person.Address.Street}, {person.Address.City}, {person.Address.State} {person.Address.Zip}");
        Console.WriteLine("Phone Numbers:");
        foreach (var phoneNumber in person.PhoneNumbers)
        {
            Console.WriteLine($"\t{phoneNumber.Type}: {phoneNumber.Number}");
        }
    }
}

This code defines classes for Person, Address, and PhoneNumber that match the structure of the JSON data. It then uses the JsonSerializer.Deserialize method to parse the JSON string and convert it into a Person object. Finally, it uses the properties of the Person object to display the data.

The output of the above program would be the data from the Person object that was created by parsing the JSON string. The output would look like this:

First Name: John
Last Name: Doe
Age: 25
Address: 123 Main St, Springfield, IL 12345
Phone Numbers:
    home: 555-555-1234
    work: 555-555-5678v

This is the same data that was represented in the JSON string, but now it is stored in a Person object and can be accessed using the properties of the object.

Here is the complete program:

using Example;
using System;
using System.Text.Json;

namespace Example
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public Address Address { get; set; }
        public PhoneNumber[] PhoneNumbers { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }

    public class PhoneNumber
    {
        public string Type { get; set; }
        public string Number { get; set; }
    }    
}

public class Program
{
    public static void Main()
    {
        SerializeExample();
        DeSerializeExample();
        
    }

    public static void SerializeExample()
    {
        var person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Age = 25,
            Address = new Address
            {
                Street = "123 Main St",
                City = "Springfield",
                State = "IL",
                Zip = "12345"
            },
            PhoneNumbers = new PhoneNumber[]
            {
                new PhoneNumber
                {
                    Type = "home",
                    Number = "555-555-1234"
                },
                new PhoneNumber
                {
                    Type = "work",
                    Number = "555-555-5678"
                }
            }
        };
        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
    }

    public static void DeSerializeExample()
    {
        string jsonString = "{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":25,\"Address\":{\"Street\":\"123 Main St\",\"City\":\"Springfield\",\"State\":\"IL\",\"Zip\":\"12345\"},\"PhoneNumbers\":[{\"Type\":\"home\",\"Number\":\"555-555-1234\"},{\"Type\":\"work\",\"Number\":\"555-555-5678\"}]}";

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

        Console.WriteLine($"First Name: {person.FirstName}");
        Console.WriteLine($"Last Name: {person.LastName}");
        Console.WriteLine($"Age: {person.Age}");
        Console.WriteLine($"Address: {person.Address.Street}, {person.Address.City}, {person.Address.State} {person.Address.Zip}");
        Console.WriteLine("Phone Numbers:");
        foreach (var phoneNumber in person.PhoneNumbers)
        {
            Console.WriteLine($"\t{phoneNumber.Type}: {phoneNumber.Number}");
        }
    }
}

Please download the complete source code attached at the top of this article.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.