Start Debugging
2023-09-05 更新日 2023-11-05 csharpdotnetdotnet-8 Edit on GitHub

.NET 8 非公開メンバーを JSON シリアライズに含める

.NET 8 で JsonInclude 属性を使って、private、protected、internal なプロパティを JSON シリアライズに含める方法を解説します。

.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

この属性は、privateprotectedinternal といった、どの非公開修飾子に対しても機能します。例を見てみましょう。

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.

< 戻る