To enable the use of a non-public property accessor, you can use the [JsonInclude]
attribute.
The following shows the usage of the [JsonInclude]
attribute.
public class Customer
{
public string Name { get; init; }
[JsonInclude]
public int Age { get; private set; }
[JsonInclude]
public string Address { private get; set; }
};
public static void Example1()
{
string json = @"{""Name"":""Mark"",""Age"":33,""Address"":""22 ashdown""}";
Console.WriteLine($"Input JSON: {json}");
Customer customerDeserialized = JsonSerializer.Deserialize<Customer>(json);
Console.WriteLine($"Name: {customerDeserialized.Name}");
Console.WriteLine($"Age: {customerDeserialized.Age}");
json = JsonSerializer.Serialize<Customer>(customerDeserialized);
Console.WriteLine($"Output JSON: {json}");
}
The above example will print the following output.
Input JSON: {"Name":"Mark","Age":33,"Address":"22 ashdown"}
Name: Mark
Age: 33
Output JSON: {"Name":"Mark","Age":33,"Address":"22 ashdown"}