NET 8 – Deserialize into non-public properties
Similar to serializing into non-public members, you can deserialize into non-public members by providing a constructor with parameters matching the non-public member names and by annotating the non-public members with the JsonInclude
attribute.
Let’s jump straight to an example:
public class MyClass
{
public MyClass(int privateProperty, int protectedProperty, int internalProperty)
{
PrivateProperty = privateProperty;
ProtectedProperty = protectedProperty;
InternalProperty = internalProperty;
}
[JsonInclude]
private int PrivateProperty { get; }
[JsonInclude]
protected int ProtectedProperty { get; }
[JsonInclude]
internal int InternalProperty { get; }
public int PublicProperty { get; set; }
}
Code language: C# (cs)
Note how we haven’t annotated PublicProperty
in any way and we haven’t included it in the constructor either. That’s not necesary, because the property is public and it has a public setter, so it can be assigned after the object instance is created.
To try out deserializing into the type defined above, we can do this:
string json = "{\"PrivateProperty\":1,\"ProtectedProperty\":2,\"InternalProperty\":3,\"PublicProperty\":4}";
var myObj = JsonSerializer.Deserialize<MyClass>(json);
Code language: C# (cs)
Dealing with multiple constructors during deserialization
In case your class has multiple constructors, you will have to guide the deserializer to the correct one using the JsonConstructorAttribute.
public MyClass() { }
[JsonConstructor]
public MyClass(int privateProperty, int protectedProperty, int internalProperty)
{
PrivateProperty = privateProperty;
ProtectedProperty = protectedProperty;
InternalProperty = internalProperty;
}
Code language: C# (cs)