C# Serializing JSON

In this tutorial we will learn how to serialize JSON in C#, using the Json.net library.

Introduction

In this tutorial we will learn how to serialize JSON in C#, using the Json.net library.

If you are using the Visual Studio IDE, you can easily install it from the NuGet Package Manager, as shown in this previous tutorial.

This tutorial was tested with .NET Core 3.1 and with version 12.03 of the Json.net library.

The code

We will start our code by declaring a Person class. We will later instantiate this class and serialize the object to a JSON string.

We are defining this class only for testing purposes, so we will follow the same structure we already used in the previous deserialization tutorial. So, it will have the following fields: a name, an age and a list of languages that the person speaks.

namespace JsonSerialize
{
    using System.Collections.Generic;

    public class Person
    {
        public Person(string name, int age, List<string> languages)
        {
            Name = name;
            Age = age;
            Languages = languages;
        }

        public string Name { get; }
        
        public int Age { get; }
        
        public List<string> Languages { get; }

    }
}

After declaring our class, we will move to the main code. The first thing we are going to do is stating the namespaces we will be using.

We will need the Newtonsoft.Json namespace, so we can access the class we need to serialize the object into a string. We will also use the System namespace, so we are able to print content to the console.

Since we are going to have to instantiate the person class and one of its parameters is a list of strings, we will also need the System.Collections.Generic namespace.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

Then, on the Main function, we will create an object of our Person class. We will pass some arbitrary values to the constructor, just for illustration purposes. Note that the languages list was created using a collection initializer.

var person = new Person(
    name: "Todd",
    age: 25,
    languages: new List<string>
    {
       "portuguese",
       "english"
    }
);

Then, to serialize the previous object into a JSON string, we just call the SerializeObject method on the JsonConvert class. As input, we pass the object we want to serialize and as output we obtain a string with the result.

string jsonString = JsonConvert.SerializeObject(person);

The previous method call will return a minified JSON string. This is useful for sending it, for example, over HTTP, since it has less characters.

Nonetheless we might want to get a more human readable JSON string, with some nice indentation. This can be done by passing an additional parameter to the SerializeObject method.

This parameter is an enumerated value of type Formatting. We should pass the value Indented.

string indentedJsonString = JsonConvert.SerializeObject(person, Formatting.Indented);

The complete code is shown below.

namespace JsonSerialize
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person(
                name: "Todd",
                age: 25,
                languages: new List<string>
                {
                    "portuguese",
                    "english"
                }
            );

            string jsonString = JsonConvert.SerializeObject(person);
            Console.WriteLine(jsonString);

            string indentedJsonString = JsonConvert.SerializeObject(person, Formatting.Indented);
            Console.WriteLine(indentedJsonString);

        }
    }
}

Testing the code

To test the code, simply compile it and run it in a tool of your choice. I’m using Visual Studio 2019.

Upon running the code, you should get an output similar to figure 1. As can be seen, we first get the JSON string in the minified format and then in the prettified format. In both cases, the values of the fields match the ones we assigned to our Person object.

Output of the program, showing the serialized JSON string.
Figure 1 – Output of the program, showing the serialized JSON string.

Leave a Reply

%d bloggers like this: