Gabriel Anton
Gabriel Anton

Reputation: 624

Use System.Text.Json to deserialize properties with private setters

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

Answers (2)

Alex Klaus
Alex Klaus

Reputation: 8934

As per the official docs (C# 9), you got 2 options:

  1. Use init instead of set on the property. E.g. public string Summary { get; init; }

  2. 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

Daniel A. White
Daniel A. White

Reputation: 190945

In .NET Core 3.x, that is not possible. In .NET 5 timeline, support has been added.

Upvotes: 14

Related Questions