System.Text.Json – Use JsonConverterFactory to serialize multiple types the same way

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: Create a custom converter for each type. Create a custom converter factory + … Read more

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

By default, the System.Text.Json.JsonSerializer only serializes public properties. If you want to serialize non-public properties, you can create a custom converter and use reflection to get the non-public properties too, like this: Use the custom converter by adding it to JsonSerializerOptions.Converters and passing the options in when serializing, like this: In this article, I’ll show … Read more

System.Text.Json – How to customize serialization with JsonConverter

Most of the time JsonSerializer will get you want you want. You can pass in options to control serialization to a certain extent. But sometimes you’ll run into scenarios where you need to customize how it handles serialization for a specific type. This is where JsonConverter comes in. To customize serialization for a specific type, … Read more

System.Text.Json.JsonException: A possible object cycle was detected which is not supported

When you use System.Text.Json.JsonSerializer to serialize an object that has a cycle, you’ll 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. This is the same problem … Read more