NET 8 – Deserialize into read-only properties
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; }
}
Code language: C# (cs)
Using JsonSerializerOptions
You can set the JsonSerializerOptions.PreferredObjectCreationHandling
property to Populate
and pass it along to the Deserialize
method.
new JsonSerializerOptions
{
PreferredObjectCreationHandling = JsonObjectCreationHandling.Populate
};
Code language: C# (cs)
One Comment