.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.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
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
};
If the obstacle is member visibility rather than a missing setter, see deserializing non-public properties in .NET 8 for the constructor and JsonInclude approach.
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.