--- lang: ja-jp breaks: true --- # System.Text.Json `[JsonInclude]` `[JsonConstructor]` 属性を付与したときの動作 2022-08-05 ## `[JsonInclude]` を付与すると、private set へのデシリアライズが可能になる。 ```csharp= [System.Text.Json.Serialization.JsonInclude] public string Field01 { get { return this.m_field01; } private set { this.m_field01 = value; } } ``` ## `[JsonInclude]` を付与しても、非公開 set へのデシリアライズは出来ない。 :::warning 以下は、デシリアライズされない。特に例外は出力されない。 ::: ```csharp= [System.Text.Json.Serialization.JsonInclude] public string Field01 { get { return this.m_field01; } } ``` ## デフォルトコンストラクタがある場合は、それによりインスタンス化された後に`[JsonInclude]`が付与されたプロパティが使用されて値がセットされる。 ```csharp= public Sample003(){} [System.Text.Json.Serialization.JsonInclude] public string Field01 { get { return this.m_field01; } private set { this.m_field01 = value; } } [System.Text.Json.Serialization.JsonInclude] public string Field02 { get { return this.m_field02; } private set { this.m_field02 = value; } } ``` ## 一部のフィールドの初期化パラメータを持つコンストラクタでインスタンス化された場合は、初期化パラメータにないプロパティのみが呼び出されてセットされる。 ```csharp= [System.Text.Json.Serialization.JsonConstructor] public Sample003( string field02 ) { this.m_field02 = field02; } [System.Text.Json.Serialization.JsonInclude] public string Field01 { get { return this.m_field01; } private set { this.m_field01 = value; } } // 以下は呼び出されない [System.Text.Json.Serialization.JsonInclude] public string Field02 { get { return this.m_field02; } private set { this.m_field02 = value; } } ``` :::info この動作は、`Newtonsoft.Json`も同様。 ::: :::info 初期化パラメータ付きコンストラクタに`[System.Text.Json.Serialization.JsonConstructor]`が無い場合は例外が送出されます。 ::: ## 初期化パラメータ付きコンストラクタのパラメータに不要なパラメータがあった場合、例外が創出される。 ```csharp= [System.Text.Json.Serialization.JsonConstructor] public Sample003( string field01, string field02, string xxxxx /* Jsonには存在しない不要なパラメータ */ ) : base() { this.m_field01 = field01; this.m_field02 = field02; } ``` :::info `Newtonsoft.Json`の場合は、名称名が一致するパラメータのみが使用されて正常に動作する。 ※上記の場合、`xxxxx`にはnullが設定されて呼び出される。 ::: ###### tags: `System.Text.Json` `JsonInclude` `シリアライズ` `デシリアライズ` `JsonConstructor`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up