Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 482
Gabriel Anton Avatar asked Sep 02 '25 02:09

Gabriel Anton


1 Answers

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.

like image 73
Alex Klaus Avatar answered Sep 04 '25 15:09

Alex Klaus