In this blog post, we will learn how we can serialize an object to Json in C#.

We will use the System.Text.Json namespace to serialize an object to Json in C#.

 

Serialize Object To Json In C# Using JsonSerializer

The static class JsonSerializer provides us the .Serialize() method to serialize an object to Json in C#.

 

Overloads:

The serialize method provides around six different overloads. The serialize method also takes an optional Type generic parameter.

 

Return:

The .Serialize() method returns a nullable string that is the serialized json of the object value that was passed to the method.

 

Serialize Object To Json In C# - Code Example

We will create an employee object that will have three property values.

public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public double Salary { get; set; } }

We will instantiate the employee object and will give some values to the employee object that we want to serialize.

var employee = new Employee { FirstName = "John", LastName = "Doe", Salary = 10000.50 };

Now, let's use the .Serialize() method to serialize this employee object to a Json string.

var serializedEmployee = JsonSerializer.Serialize(employee);

 

Output:

{"FirstName":"John","LastName":"Doe","Salary":10000.5}

 

Serialize Object To Json In C# - Indented Json

Now that we know how we can serialize Json, we will use the JsonSerializerOptions and create an indented Json.

Using the same example as above, we will now create the JsonSerializerOptions and indent our Json.

var options = new JsonSerializerOptions { WriteIndented = true }; var serializedEmployee = JsonSerializer.Serialize(employee, options);

 

Output:

{ "FirstName": "John", "LastName": "Doe", "Salary": 10000.5 }

 

Serialize Object To Json In C# - Serialize To Camel Case Json

In this code example, we will use the JsonSerializerOptions to serialize our object to create Camel Case Json properties.

var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var serializedEmployee = JsonSerializer.Serialize(employee, options);

 

Output:

{ "firstName": "John", "lastName": "Doe", "salary": 10000.5 }