C# – Convert an object to JSON and vice versa

The simplest way to convert an object to JSON (serialization) is to use the built-in System.Text.Json.JsonSerializer:

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 defualt). 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)

To do the opposite – convert a JSON string to an object (deserialization) – use Deserialize<T>():

using System.Text.Json; var movie = JsonSerializer.Deserialize<Movie>(json);
Code language: C# (cs)

This deserializes the JSON string to a Movie object using the default settings.

JSON serialization settings

You can change the serialization settings by passing in a JsonSerializerOptions object. Reuse the JsonSerializerOptions object to greatly improve performance.

There are many settings. I’ll show a few common ones below. If the settings aren’t getting you what you want, you can also write a custom converter to deal with your specific JSON serialization scenario.

Pretty print

To make the JSON easier for people to read, pretty print it by using WriteIndented=true:

var settings = new JsonSerializerOptions() { WriteIndented = true }; var json = JsonSerializer.Serialize(movie, settings);
Code language: C# (cs)

This generates 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)

Camel casing

By default, JsonSerializer will read/write property names exactly as they are. In .NET, the convention is to use pascal casing for property names (ex: PropertyName). You can make it use camel casing by setting PropertyNamingPolicy to JsonNamingPolicy.CamelCase:

var settings = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; //generates camel-cased JSON var json = JsonSerializer.Serialize(movie, settings); //can handle camel-cased JSON var newMovie = JsonSerializer.Deserialize<Movie>(json);
Code language: C# (cs)

This allows you to handle JSON with camel-cased property names, like this:

{ "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)

Ignore null properties

If you don’t want the JSON to include null properties (ex: “title”:null), you can make it ignore null properties during serialization by using JsonIgnoreCondition.WhenWritingNull:

var writer = new Writer() { FirstName = "Joanne", MiddleName = null, LastName = "Rowling", PenName = "J.K. Rowling" }; //Yep, no middle name! var settings = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; var json = JsonSerializer.Serialize(writer, settings);
Code language: C# (cs)

This generates the following JSON. Notice how it doesn’t have the MiddleName property:

{"FirstName":"Joanne","LastName":"Rowling","PenName":"J.K. Rowling"}
Code language: JSON / JSON with Comments (json)

Web defaults

You can initialize JsonSerializerOptions with JsonSerializerDefaults.Web (this is what ASP.NET uses). This makes it use the following settings (currently):

Here’s an example of using this to serialize:

var settings = new JsonSerializerOptions(JsonSerializerDefaults.Web); var json = JsonSerializer.Serialize(new Person() { Name = "Bob" }, settings);
Code language: C# (cs)

This generates the following JSON. Notice “name” is camel-cased:

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

Getting System.Text.Json

For .NET Core 3.0 and above, System.Text.Json is included in the framework.

For versions before that, you can install the System.Text.Json package (View > Other Windows > Package Manager Console):

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

This is available for versions back to .NET Framework 4.6.1.

Using Newtonsoft.Json

Newtonsoft.Json was the de facto JSON serialization library for several years. Microsoft started developing System.Text.Json as a long-term replacement for Newtonsoft.Json. If you want to (or have to) use Newtonsoft, here’s a quick introduction.

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

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

To convert an object to JSON (serialization), use JsonConvert.SerializeObject():

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 how easy it is to pretty print? Just have to pass in Formatting.Indented instead of needing to pass in a settings object.

To convert JSON to an object (deserialization), use DeserializeObject<T>():

using Newtonsoft.Json; var newMovie = JsonConvert.DeserializeObject<Movie>(json);
Code language: C# (cs)

You can change the 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 json = JsonConvert.SerializeObject(new Person() { Name = "Nandor" }, settings);
Code language: C# (cs)

This generates the following JSON:

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

Leave a Comment