C# – Deserializing JSON with quoted numbers

There are two ways to represent numbers in JSON: as number literals (ex: 123) or as quoted numbers (ex: “123”). In this article, I’ll explain how quoted numbers are handled during deserialization in Newtonsoft and System.Text.Json and how to change the behavior. At the end, I’ll show how to write quoted numbers during serialization. Quoted … Read more

ASP.NET Core – Configure JSON serializer options

ASP.NET Core uses System.Text.Json as the default JSON serializer. To configure the JSON serializer options, call AddJsonOptions() in the initialization code: Calling AddJsonOptions() gives you access to the global JsonSerializerOptions object. This is used for all requests / responses. You can configure the options and add converters (including your own custom JSON converters). ASP.NET Core’s … Read more

How to use Newtonsoft in ASP.NET Core

By default, ASP.NET Core uses System.Text.Json for JSON serialization. If you want to use Newtonsoft instead: Note: Before .NET 6, do this in Startup.ConfigureServices(). Install the right package Microsoft packaged up Microsoft.AspNetCore.Mvc.NewtonsoftJson based on the framework version, so you can’t just install the latest package. You have to find the latest one for the framework … Read more

C# – Newtonsoft extension methods for HttpClient

System.Net.Http.Json provides extension methods that simplify getting and sending JSON with HttpClient. Internally, it uses System.Text.Json for serialization. What if you want to use Newtonsoft instead of System.Text.Json? You can use the following extension methods for that: These are modeled off of the extension methods in System.Net.Http.Json. You can pass in a JsonSerializerSettings object to … Read more

C# – Get and send JSON with HttpClient

The simplest way to get and send JSON with HttpClient is to use the GetFromJsonAsync() and PostAsJsonAsync() extension methods found in System.Net.Http.Json, like this: Note: You have to install the System.Net.Http.Json nuget package if you’re using a framework version before .NET 5. These extension methods use System.Text.Json for serialization. They simplify things by abstracting away … Read more

C# – Serialize anonymous types with System.Text.Json

It’s common to need to customize serialization. When you need to do this, you’d typically need to create a custom converter and pass it in during serialization. Depending on your scenario, an alternative approach is to use anonymous types, like this: Basically you select properties from another object and format them as desired, and then … Read more

C# – How to use JsonConverterFactory

Let’s say you want to serialize the four datetime types – DateTime, DateTime?, DateTimeOffset, and DateTimeOffset? – in the same way. You want to serialize them to use the US date style (ex: 7/14/2021). There are two main ways to accomplish this: 1) Create a custom JsonConverter for each type or 2) Create a JsonConverterFactory … Read more

System.Text.Json – How to serialize non-public properties

By default, System.Text.Json.JsonSerializer only serializes public properties. If you want to serialize non-public properties, you have two options: In this article, I’ll show examples of both approaches for handling non-public properties. Updated 2022-02-22 to explain the new JsonInclude attribute added in .NET 5. Write a custom JSON converter to serialize non-public properties When the built-in … Read more

The JSON value could not be converted to System.DateTime

When you’re using System.Text.Json to deserialize a DateTime value, if the value isn’t in the format it expects, then it’ll throw a JsonException. It expects datetimes to be in the ISO-8601-1:2019 format (for example: 2021-07-12T12:35:34+00:00). For example, the following code is trying to deserialize a DateTime value in an unexpected format: This’ll throw the following … Read more

C# – Create a custom JsonConverter for System.Text.Json

Most of the time System.Text.Json will get you want you want. You can pass in options to control JSON serialization and deserialization to a certain extent. But sometimes you’ll run into scenarios where you need to customize how it handles a specific type. This is where JsonConverter comes in. You can customize serialization / deserialization … Read more

JsonException: A possible object cycle was detected

When you use System.Text.Json.JsonSerializer to serialize an object that has a cycle, you get the following exception: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 0. In .NET 6+, you can … Read more

C# – Serialize a tuple to JSON

When you serialize a tuple to JSON, it uses the the underlying ValueTuple’s field names – Item1 and Item2. It doesn’t matter if you’re using a named tuple, it won’t use the names you specified in the tuple declaration. This behavior is the same with Newtonsoft and System.Text.Json. Here’s an example of serializing a named … Read more

Querying JSON in SQL Server

In SQL Server 2016, Microsoft added support for handling JSON data: The JSON API in SQL Server is well-suited for simple scenarios where you only need to do basic querying and manipulation. For advanced querying, the SQL Server JSON API gets complicated and hard to use, so you may want to look into other options. … Read more

Serializer options cannot be changed once serialization or deserialization has occurred

Problem When using System.Text.Json, it’s a good idea to reuse JsonSerializerOptions objects. This leads to a massive 200x speedup in subsequent calls to the serializer. The downside is you can’t change properties on the options object after you’ve passed it in a Serialize()/Deserialize() call. You’ll get the exception: System.InvalidOperationException: Serializer options cannot be changed once … Read more

C# – How to read configuration from appsettings.json

The appsettings.json file is a convenient way to store and retrieve your application’s configuration. You can add it to any project and then use the Microsoft.Extensions.Configuration library to work with it. Since appsettings.json is just a JSON file, you can add any section / values you want (this is easier than working with XML-based app.config … Read more

C# – Reuse JsonSerializerOptions for performance

Reusing JsonSerializerOptions (from System.Text.Json) is optimal for performance. It caches type info, which results in a 200x speedup when it deals with the type again. Therefore, always try to reuse JsonSerializerOptions. I’ll show a speed comparison of serializing with and without reusing JsonSerializerOptions. Measuring the performance gains of reusing JsonSerializerOptions To measure the performance gains … Read more

Newtonsoft: Self referencing loop detected for property

Problem When you try to serialize an object using Newtonsoft.Json and there’s a circular reference, you get the following exception: Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property Here’s an example of code that results in this exception: The Parent object references the Child object, which references the Parent object. Hence, a circular reference (aka a … Read more

JsonException: The JSON value could not be converted to Enum

When you’re using System.Text.Json to deserialize JSON that contains the string representation of an enum, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to <Enum Type> The following JSON would cause this exception. Conference is an enum, and this is using the string representation “NFC” instead of the numeric value … Read more

C# – Case sensitivity in JSON deserialization

By default Newtonsoft does case insensitive JSON deserialization and System.Text.Json does case sensitive JSON deserialization. Case sensitivity comes into play when a JSON string is being deserialized into an object. If you’re using case sensitive deserialization, then keys in the JSON string must match type names exactly, otherwise it won’t deserialize the class/property with the … Read more

System.Text.Json can’t serialize Dictionary unless it has a string key

Before .NET 5, the built-in JSON serializer (System.Text.Json) couldn’t handle serializing a dictionary unless it had a string key. Here’s an example running in .NET Core 3.1 to show the problem. This is initializing a dictionary with values and then attempting to serialize it. This results in exception: System.NotSupportedException: The collection type ‘System.Collections.Generic.Dictionary`2[System.Int32,System.String]’ is not … Read more

Common Newtonsoft.Json options in System.Text.Json

If you’re switching from Newtonsoft.Json to System.Text.Json (or vice versa), you may be wondering how to specify the common options you’re used to using in Newtonsoft. For example, how do you specify the equivalent of Newtonsoft.Json.Converters.StringEnumConverter in System.Text.Json? The following table shows a few common serialization options used in Newtonsoft.Json and their equivalents in System.Text.Json. … Read more

C# – Deserialize JSON to dynamic object

If you want to deserialize JSON without having to create a bunch of classes, you can either deserialize to a dictionary or deserialize to a dynamic object with Newtonsoft.Json. Here’s an example. Let’s say you want to deserialize the following JSON: To deserialize this to a dynamic object with Newtonsoft, use JsonConvert.DeserializeObject<dynamic>: This outputs the … Read more