C# – Ignore null properties during JSON serialization

By default, null properties are included during JSON serialization like this: There are two ways to ignore null properties: In this article, I’ll show examples of these two ways to ignore null properties. I’ll show how to do it with System.Text.Json and Newtonsoft. Ignore null properties with System.Text.Json Use JsonIgnoreCondition.WhenWritingNull to ignore null properties. You … Read more

C# – Use records as a shortcut for defining DTOs

You can declare a record with a single line of code: Note: This feature was added in .NET 5 / C# 9. Records are basically classes (reference types) that work very well as simple data containers (i.e. DTOs). Here’s an example of using a record: This outputs the following: As shown, when you declare a … 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

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