20

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)

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Gabriel Anton
  • 444
  • 1
  • 6
  • 14

2 Answers2

30

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.

Alex Klaus
  • 8,168
  • 8
  • 71
  • 87
  • 1
    Indeed, `init` it's a powerful concept and will do the job gracefully in such like situations. `[JsonInclude]` it is what i was looking for, but it is only available in .NET 5. – Gabriel Anton Apr 23 '21 at 15:00
  • Beware though if you use JsonInclude-trickery to serialize lists: If the getter is public, you can also read-/write-access individual elements, if no further trickery is used. – Sebastian Mach Dec 08 '21 at 07:15
  • what about support for `private readonly` *fields*? – JobaDiniz Aug 06 '22 at 19:52
  • It's a fair comment. Thanks @JobaDiniz. Yes, it's possible, I updated the answer. – Alex Klaus Aug 08 '22 at 06:53
  • 1
    Your remark about `JsonInclude` is not correct, sadly. "When applied to a property, indicates that non-public getters and setters can be used for serialization and deserialization. Non-public properties are not supported." – greenoldman Oct 14 '22 at 19:19
  • 1
    @greenoldman, not sure where the message you're quoting is coming from. [Here's an example](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/immutability?pivots=dotnet-6-0#non-public-property-accessors) from Microsoft for "_Non-public property accessors_" that shows the trick for `[JsonInclude]` – Alex Klaus Oct 17 '22 at 02:02
  • @AlexKlaus The quote comes from the linked docs. Sadly for me, MS make a difference between private member and public member with private access. – greenoldman Oct 17 '22 at 15:16
14

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    Beware though if you use JsonInclude-trickery to serialize lists: If the getter is public, you can also read-/write-access individual elements, if no further trickery is used. – Sebastian Mach Dec 08 '21 at 07:15
  • 2
    Looks like newtonsoft is still on the table, having to go through all this trickery just to substitute "it just works" behavior is getting old at this point :/ – Douglas Gaskell Sep 22 '22 at 02:36