C# – Deserialize JSON with a specific constructor

When your class has multiple constructors, you can use the JsonConstructor attribute to specify which constructor to use during deserialization. Here’s an example. The Person class has two constructors. I put the JsonConstructor attribute on one of the constructors: Note: JsonConstructor for System.Text.Json was added in .NET 5. Now deserialize a JSON string to the … Read more

C# – Changing the JSON serialization date format

When you serialize a date with System.Text.Json, it uses the standard ISO-8601 date format (ex: “2022-01-31T13:15:05.2151663-05:00”). Internally, it uses the built-in DateTimeConverter class for handling DateTime, which doesn’t give you a way to change the date format. To change the date format, you have to create a custom JSON converter and pass it in: This … 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