I have a (C#) object that I want to serialize using the .NET 6 System.Text.Json serializer. My object looks like so:
private List<Substitution> _substitutions;
public string? Name { get; private set; }
public string EmailAddress { get; private set; }
public IReadOnlyCollection<Substitution> Substitutions => _substitutions.AsReadOnly();
When I instanciate is and serialize it, I get a JSON string that looks like expected:
{
"Name":"Foo Bar",
"EmailAddress":"my-email@domain.com",
"Substitutions":[
{"Key":"Firstname","Value":"Foo"},
{"Key":"Lastname","Value":"Bar"}
]
}
Now when I try to deserialize this value back to an object, I get this fancy error:
Each parameter in the deserialization constructor on type 'objectname' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.'
I already pretty much found out the IReadOnlyCollection is the problem here. It is listed in the supported data types for JSON Serialization / Deserialization so I expected this to work. The error describes that a constructor is missing accepting all the fields serialized. I played a little bit with the casing so the fields in JSON match the names of the properties, unfortunately without success.
The object contains this constructor:
public Recipient(string name, string emailAddress, List<Substitution> substitutions)
{
EmailAddress = emailAddress;
Name = name;
_substitutions = substitutions;
}
I thought I was fine there, but apparently not ;) The idea is that I want to maintain the list of substitutions within the object so exposing a ready-only copy is mandatory behavior.
My question is, how to deserialize this object correctly? Thanks a bunch!