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

.NET 8 読み取り専用プロパティへのデシリアライズ

.NET 8 で setter のない読み取り専用プロパティに対して、JsonObjectCreationHandling や JsonSerializerOptions を使って JSON をデシリアライズする方法を解説します。

.NET 8 から、set アクセサーを持たないプロパティに対してもデシリアライズできるようになりました。この挙動は JsonSerializerOptions で有効化することもできますし、JsonObjectCreationHandling 属性を使って型ごとに有効化することもできます。

JsonObjectCreationHandling 属性を使う

型に System.Text.Json.Serialization.JsonObjectCreationHandling 属性を付け、オプションをパラメーターとして渡します。

[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
public class Foo
{
     public int Bar { get; }
}

JsonSerializerOptions を使う

JsonSerializerOptions.PreferredObjectCreationHandling プロパティを Populate に設定し、それを Deserialize メソッドに渡します。

new JsonSerializerOptions 
{ 
    PreferredObjectCreationHandling = JsonObjectCreationHandling.Populate
};

Comments

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

< 戻る