Json.Net JsonConstructor attribute alternative for System.Text.Json

Viewed 2267

In Json.Net we have JsonConstructor attribute in order to instruct deserializer that should use the constructor to create the object.

Is there alternative in System.Text.Json?

2 Answers

Please try this library I wrote as an extension to System.Text.Json to offer polymorphism: https://github.com/dahomey-technologies/Dahomey.Json

Add [JsonConstructor] attribute defined in the namespace Dahomey.Json.Attributes on your class.

public class ObjectWithConstructor
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    [JsonConstructor]
    public ObjectWithConstructor(int id, string name)
    {
        Id = id;
        Name = name;
    }
}

Setup json extensions by calling on JsonSerializerOptions the extension method SetupExtensions defined in the namespace Dahomey.Json. Then deserialize your class with the regular Sytem.Text.Json API.

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();

const string json = @"{""Id"":12,""Name"":""foo"",""Age"":13}";
ObjectWithConstructor obj = JsonSerializer.Deserialize<ObjectWithConstructor>(json, options);
Related