C# Serialization By Transforming Objects into A JSON String

Serialization By Transforming Objects into A JSON String Banner Image

Introduction

In C#, JSON is a format that is a common structure that can be transferred between different languages and applications. C#'s go-to serializer is JsonSerializer. Serialization is when we transform a class object into a string. This includes complex classes with many different types and data structures can be changed to a form of a string. It is useful for inter-application communications, especially for web applications that need to transfer data over the Internet. Since JSON is widely used many languages support the serialization of objects to a JSON format. The advantages are that is easy to read relative to XML, fast and you don't need to write your function for communicating over the wire.

Serialization History

C#, has had a long and complicated history of supporting serializing an object.

Initially there wasn't support for serialzing into JSON and .NET relied on Newtonsoft.JSON for many years. Newtonsoft.JSON is easy to use and has been in use for a long time. Below are other attempts for .NET to implement a JSON serlizier

Json.Decode in the System.Web.Helpers namespace does not work with the .NET framework and is restricted to ASP.NET Web Pages.

JsonQueryStringConverter.ConvertStringToValue in System.ServiceModel.Web didn't work with .NET latest. It has the latest support was .NET 4.8.1.

JavaScriptSerializer.Deserialize is only supported up to .NET 4.8.1 and Microsoft recommends not using it but rather using JsonSerializer in the System.Text.Json namespace for greater than 4.7.2 and for earlier versions to use JSON.NET.

System.Json was designed for Silverlight and is no longer supported for many years.

Windows.Data.Json JsonValue is very specific to Windows 8.x and Windows phone 8.x development

JsonSerializer Serialize Method

Serialize Object To JSON Chart

In 2019, C# has started from scratch its latest JSON Serializer into the System.Text.Json namespace. This is the go to way to serilzation in C#.

Below are some examples serializing of various .NET types and a custom class with these building blocks you need to create any JSON.

Microsoft recommends using this method for greater than .NET 4.7.2.

JsonSerializer Deserialize Various Types Code Example

Serialize Object To JSON Syntax Image

This calls a simple one-line method. You need to provide the type of object to convert the JSON string too. Then pass the string to the method.

using System.Text.Json;

// Serialize string
string jsonString = "Hello, World!";
string serializedString = JsonSerializer.Serialize<string>(jsonString);
Console.WriteLine("string");
Console.WriteLine(serializedString);
Console.WriteLine();


// Serialize int
int jsonInt = 42;
serializedString = JsonSerializer.Serialize<int>(jsonInt);
Console.WriteLine("int");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize char
char jsonChar = 'A';
serializedString = JsonSerializer.Serialize<char>(jsonChar);
Console.WriteLine("char");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize bool
bool jsonBool = true;
serializedString = JsonSerializer.Serialize<bool>(jsonBool);
Console.WriteLine("bool");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize float
float jsonFloat = 3.14f;
serializedString = JsonSerializer.Serialize<float>(jsonFloat);
Console.WriteLine("float");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize double
double jsonDouble = 2.71828;
serializedString = JsonSerializer.Serialize<double>(jsonDouble);
Console.WriteLine("double");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize List<string>
List<string> jsonList = new List<string>() { "apple", "banana", "cherry" };
serializedString = JsonSerializer.Serialize<List<string>>(jsonList);
Console.WriteLine("List<string>");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize Dictionary<string, int>
Dictionary<string, int> jsonDictionary = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };
serializedString = JsonSerializer.Serialize<Dictionary<string, int>>(jsonDictionary);
Console.WriteLine("Dictionary<string, int>");
Console.WriteLine(serializedString);
Console.WriteLine();

// Serialize array
//raw JSON:[1,2,3,4,5]
int[] jsonArray = new int[5] { 1, 2, 3, 4, 5 };
serializedString = JsonSerializer.Serialize<int[]>(jsonArray);
Console.WriteLine("array");
Console.WriteLine(serializedString);
Console.WriteLine();

JsonSerializer Serialize Various Types Code Output

string
"Hello, World!"

int
42

char
"A"

bool
true

float
3.14

double
2.71828

List<string>
["apple","banana","cherry"]

Dictionary<string, int>
{"one":1,"two":2,"three":3}

array
[1,2,3,4,5]

JsonSerializer Serialize Class Code Example

Now you can put all these types into a class for better encapsulation. See example below.


using System.Text.Json;

Student student = new Student();
student.Name = "John Mark";
student.Age = 20;
student.Grade = 'B';
student.IsPresent = true;
student.GPA = 4.2f;
student.Height = 110.5;
student.Grades = new Dictionary<string, int>();
student.Grades.Add("Math", 92);
student.Grades.Add("Cooking", 99);
student.Subjects = new List<string>();
student.Subjects.Add("English");
student.Subjects.Add("Math");
student.Subjects.Add("Cooking");
student.CustomClasses = new CustomClass[2] { new CustomClass("Cooking", 231), new CustomClass("Engineering",21) };


// Serializing the Student class to JSON string 
string serializedJSON = JsonSerializer.Serialize<Student>(student);//Convert JSON String to an object
Console.WriteLine(serializedJSON);



public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public char Grade { get; set; }
    public bool IsPresent { get; set; }
    public float GPA { get; set; }
    public double Height { get; set; }
    public Dictionary<string, int> Grades { get; set; }
    public List<string> Subjects { get; set; }
    public CustomClass[] CustomClasses { get; set; }

}

public class CustomClass
{
    public string ClassName { get; set; }
    public int ClassId { get; set; }

    public CustomClass(string className, int classId)
    {
        ClassName = className;
        ClassId = classId;
    }
}

Code Output
{"Name":"John Mark","Age":20,"Grade":"B","IsPresent":true,"GPA":4.2,"Height":110.5,"Grades":{"Math":92,"Cooking":99},"Subjects":["English","Math","Cooking"],"CustomClasses":[{"ClassName":"Cooking","ClassId":231},{"ClassName":"Engineering","ClassId":21}]}

If you want to know how to change a JSON back into a object then check out The Best C# Deserializer To Convert JSON To An Object

Get Latest Updates