Start Debugging
2023-09-03 Updated 2023-11-05 dotnetdotnet-8

.NET 8 – Deserialize into read-only properties

Learn how to deserialize JSON into read-only properties without a setter in .NET 8 using JsonObjectCreationHandling or JsonSerializerOptions.

Starting with .NET 8 you can deserialize into properties which do not have a set accessor. You can opt-in for this behavior using JsonSerializerOptions, or on a per-type basis using the JsonObjectCreationHandling attribute.

Using JsonObjectCreationHandling attribute

You can annotate your type with the System.Text.Json.Serialization.JsonObjectCreationHandling attribute, passing your option as a parameter.

[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
public class Foo
{
     public int Bar { get; }
}

Using JsonSerializerOptions

You can set the JsonSerializerOptions.PreferredObjectCreationHandling property to Populate and pass it along to the Deserialize method.

new JsonSerializerOptions 
{ 
    PreferredObjectCreationHandling = JsonObjectCreationHandling.Populate
};
< Back