System.Text.Json Constructor and immutable type

Viewed 222

I have a lot of immutable DTOs which I need to deserialize from JSON. Json.NET automatically uses a public constructor should it find one. However, System.Text.Json seems to require a [JsonConstructor] attribute (even if there is only one constructor). I am unable to add this to all my classes/structs. Is there an easy solution?

e.g. Deserializes fine:

public readonly struct Model
{
    public string Value { get; }

    [JsonConstructor]
    public Model(string value)
    {
        Value = value
    }
}

Does not work:

public readonly struct Model
{
    public string Value { get; }

    public Model(string value)
    {
        Value = value
    }
}
0 Answers
Related