2

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
  • 2
    Not currently implemented, see System.Text.Json: Custom Constructor Support #40399 For the 3.0 release, there is no planned additional support for calling a non-default constructor during deserialization. That would have to be done by a custom converter. Commented Oct 18, 2019 at 15:29
  • Should I make that an answer? Commented Oct 18, 2019 at 22:26

2 Answers 2

2

Looks like this has now been added as of .NET 5.0 Preview 8:

Announcing .NET 5.0 Preview 8

JsonSerializer improvements in .NET 5

Related issue: JsonSerializer support for immutable classes and structs

Related pull request: Add [JsonConstructor] and support for deserializing with parameterized ctors

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.