Step-By-Step Guide to Serialize and Deserialize JSON Using System.Text.Json

The post is based on .NET Core 3.0 Preview version.

Update : In preview 7 few changes were made to the API. For serialization use Serialize method instead of ToString and Deserialize method instead of Parse. Post updated to reflect these changes. SDK version : 3.0.100-preview7-012821

In the last post, I have already given an overview of the System.Text.Json API that is going to be introduced with the release with .NET Core 3.0. This API will replace the Json.NET library by Newtonsoft which is baked into the framework for doing serialization and deserialization of JSON. You can read more about it using this link.

Step 1: Refer the namespaces

Add the following lines in your code. If you are working .NET Core 3 project, then there is no need to add any NuGet packages to your project. For .NET Standard and .NET Framework project, install the System.Text.Json NuGet package. Make sure that Preview is enabled and select install version 4.6.0-preview6.19303.8 or higher

using System.Text.Json;
using System.Text.Json.Serialization;

Step 2: Serializing an object into JSON string

Serialization is the process of converting an object into a format that can be saved. JSON is one of the most preferred format for encoding object into strings. You will be able to do this conversion by calling the ToString method in the JsonSerializer class available in the System.Text.Json API

For example, to convert a Dictionary object to a JSON string we can use the following statement

JsonSerializer.ToString<Dictionary<string,object>>(dictObj)

Code Snippet

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string,object> dictObj = new Dictionary<string,object>();

            dictObj.Add("name","Amal");
            dictObj.Add("age",20);
            dictObj.Add("country","India");
            
            Console.WriteLine("\nJSON Object");
            Console.WriteLine("=========================\n");
            foreach(var item in dictObj )
            {
                    Console.WriteLine($"{item.Key} -> {item.Value}");
            }
            Console.WriteLine("\nConverting back to text");
            Console.WriteLine("=========================\n");
            Console.WriteLine(JsonSerializer.ToString<Dictionary<string,object>>(dictObj));
            Console.ReadLine();
        }
    }
}

Output

  Serializing dictionary object to json using .NET Core 3.0 JSON API


Step 3: Deserializing JSON

Deserialization is the process of converting a string in JSON format to a custom data type. Consider the following JSON string which has got three properties namely name, age, and country that needs to be converted to a Dictionary object

{ "name":"Amal", "age":20 , "country": "India" }

For that, we can make use of the Parse method available in the JsonSerializer class as shown below

var items = JsonSerializer.Parse<Dictionary<string,object>>(jsonString);

The above statement will convert the string into a Dictionary object and we will be able to refer these using the Key and Value properties. Full code is given below along with the output.

Code Snippet

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using System.Collections.Generic;

namespace JsonTextApi
{
    class Program
    {
        static void Main(string[] args)
        {
            var jsonString = "{ \"name\":\"Amal\", \"age\":20 , \"country\": \"India\" }";
            Console.WriteLine("\nInput String");
            Console.WriteLine("=========================\n");
            Console.WriteLine(jsonString);
            Console.WriteLine("\nConverting text");
            Console.WriteLine("========================\n");
var items =JsonSerializer.Parse<Dictionary<string,object>>(jsonString); foreach(var item in items) { Console.WriteLine($"{item.Key} -> {item.Value}"); } Console.ReadLine(); } } }

Output

Deserializing json string to dictionary object using .NET Core 3.0 JSON API

Part 1 : Serializing and Deserializing Json in .NET Core 3.0 using System.Text.Json API


No Comments

Add a Comment

Recent Posts