C# – Convert an object to JSON

Converting an object to a JSON string is referred to as serialization. The best way to do serialization is by using a good JSON serializer. There are two primary options:

  • Use JsonSerializer.Serialize(), the built-in option (System.Text.Json).
  • Use JsonConvert.SerializeObject() (from Newtonsoft).

I’ll show examples of both options below.

Using JsonSerializer.Serialize() (in the built-in System.Text.Json)

Here’s an example of using the built-in JsonSerializer.Serialize() (in System.Text.Json) to convert an object to a JSON string:

using System.Text.Json;

var movie = new Movie()
{
	Title = "A Quiet Place Part II",
	RuntimeMinutes = 97,
	ImdbRating = 7.3m,
	ReleaseDate = new DateTime(year: 2021, month: 5, day: 28),
	OnlyReleasedInTheatres = false
};

var json = JsonSerializer.Serialize(movie);
Code language: C# (cs)

This serializes the Movie object to JSON using the default serialization settings (notice it’s not pretty printed by default). Here’s the JSON this produces:

{"Title":"A Quiet Place Part II","RuntimeMinutes":97,"ImdbRating":7.3,"ReleaseDate":"2021-05-28T00:00:00","OnlyReleasedInTheatres":false,"PopcornEaten":null}Code language: JSON / JSON with Comments (json)

Passing in JsonSerializerOptions

You can change the serialization settings by passing in JsonSerializerOptions. Here’s an example of using this to pretty print:

var settings = new JsonSerializerOptions()
{
	WriteIndented = true
};

var json = JsonSerializer.Serialize(movie, settings);
Code language: C# (cs)

This outputs the following pretty printed JSON:

{
  "Title": "A Quiet Place Part II",
  "RuntimeMinutes": 97,
  "ImdbRating": 7.3,
  "ReleaseDate": "2021-05-28T00:00:00",
  "OnlyReleasedInTheatres": false,
  "PopcornEaten": null
}Code language: JSON / JSON with Comments (json)

If you need further customization that the serializer options don’t provide, you can write a custom converter.

Getting System.Text.Json in previous versions

If System.Text.Json isn’t part of the .NET version you’re using, check if you can install the System.Text.Json package. This is compatible with many versions of .NET.

Install-Package System.Text.Json
Code language: PowerShell (powershell)

Using JsonConvert.SerializeObject() (from Newtonsoft)

First, install the Newtonsoft.Json package (View > Other Windows > Package Manager Console):

Install-Package Newtonsoft.Json
Code language: PowerShell (powershell)

Then use JsonConvert.SerializeObject() to convert an object to a JSON string. Here’s an example:

using Newtonsoft.Json;

var movie = new Movie()
{
	Title = "A Quiet Place Part II",
	RuntimeMinutes = 97,
	ImdbRating = 7.3m,
	ReleaseDate = new DateTime(year: 2021, month: 5, day: 28),
	OnlyReleasedInTheatres = false,
	PopcornEaten = null
};

var json = JsonConvert.SerializeObject(movie, Formatting.Indented);
Code language: C# (cs)

This generates the following JSON:

{
  "Title": "A Quiet Place Part II",
  "RuntimeMinutes": 97,
  "ImdbRating": 7.3,
  "ReleaseDate": "2021-05-28T00:00:00",
  "OnlyReleasedInTheatres": false,
  "PopcornEaten": null
}Code language: JSON / JSON with Comments (json)

Notice that this is pretty printed (indented for readability). To do that, you have to pass in the Formatting.Indented parameter.

Passing in JsonSerializerSettings

You can change more serialization settings by passing in JsonSerializerSettings. For example, this is pretty printing and camel casing the property names:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

var settings = new JsonSerializerSettings()
{
	ContractResolver = new CamelCasePropertyNamesContractResolver(),
	Formatting = Formatting.Indented
};

var person = new Person() { Name = "Nandor" };

var json = JsonConvert.SerializeObject(person, settings);
Code language: C# (cs)

This generates the following JSON:

{
  "name": "Nandor"
}Code language: JSON / JSON with Comments (json)

Leave a Comment