Reputation: 624
Is there a way to use System.Text.Json.JsonSerializer.Deserialize with object that contains private setters properties, and fill those properties? (like Newtonsoft.Json does)
Upvotes: 31
Views: 23827
Reputation: 8934
As per the official docs (C# 9), you got 2 options:
Use init
instead of set
on the property. E.g. public string Summary { get; init; }
Add JsonInclude
attribute on the properties with private setters. E.g.
[JsonInclude]
public string Summary { get; private set; }
A bonus option (starting from .NET 5) would be handling private
fields by either adding the same JsonInclude
attribute (docs) or setting JsonSerializerOptions.IncludeFields
option (example). Would it be ideologically correct is a different question...
Either way, JsonSerializer.DeserializeAsync will do it for you.
Upvotes: 51
Reputation: 190945
In .NET Core 3.x, that is not possible. In .NET 5 timeline, support has been added.
Upvotes: 14