Start Debugging
2023-09-05 Обновлено 2023-11-05 csharpdotnetdotnet-8 Edit on GitHub

.NET 8 включаем непубличные члены в JSON-сериализацию

Узнайте, как в .NET 8 включить private, protected и internal свойства в JSON-сериализацию с помощью атрибута JsonInclude.

Начиная с .NET 8 можно включать непубличные свойства в сериализацию при использовании System.Text.Json. Для этого достаточно пометить непубличное свойство атрибутом JsonIncludeAttribute.

[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed class JsonIncludeAttribute : System.Text.Json.Serialization.JsonAttribute

Атрибут работает с любыми непубличными модификаторами: private, protected или internal. Рассмотрим пример:

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; }
}

Как и ожидается, в выводе получим:

{"PrivateProperty":1,"ProtectedProperty":2,"InternalProperty":3}

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.

< Назад