NET 8 – Include non-public members in JSON serialization
Starting with .NET 8 you can include non public properties in the serialization when using System.Text.Json.
To do so, simply decorate the non-public property with the JsonIncludeAttribute attribute.
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed class JsonIncludeAttribute : System.Text.Json.Serialization.JsonAttribute
Code language: C# (cs)
The attribute works with any non-public modifier, such as private
, protected
or internal
. Let’s look at an example:
string json = JsonSerializer.Serialize(new MyClass(1, 2, 3));
Console.WriteLine(json);
public class MyClass
{
public MyClass(int privateProperty, int protectedProperty, int internalProperty)
{
PrivateProperty = privateProperty;
ProtectedProperty = protectedProperty;
InternalProperty = internalProperty;
}
[JsonInclude]
private int PrivateProperty { get; }
[JsonInclude]
protected int ProtectedProperty { get; }
[JsonInclude]
internal int InternalProperty { get; }
}
Code language: C# (cs)
As expected, this will output the following:
{"PrivateProperty":1,"ProtectedProperty":2,"InternalProperty":3}
Code language: JSON / JSON with Comments (json)
2 Comments