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?
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?
Looks like this has now been added as of .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
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);