Newtonsoft.Json.NET を使用して JSON を IEnumerable
チャレンジ:
複雑な JSON データを IEnumerable<BaseType>
にデシリアライズすることは困難を伴います (BaseType
は抽象です)。 標準 JsonConvert.DeserializeObject
は、抽象基本型が原因で失敗します。
解決策:
この解決策には、JsonSerializerSettings
とその TypeNameHandling
プロパティを活用することが含まれます。 TypeNameHandling
を All
に設定すると、シリアル化された JSON に $type
フィールドが含まれるようになり、逆シリアル化に重要な型情報が保持されます。
実装手順:
JsonSerializerSettings
オブジェクトを作成し、TypeNameHandling
を All
に設定します。JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
$type
フィールドが JSON 文字列に追加されます。string strJson = JsonConvert.SerializeObject(instance, settings);
結果の JSON は次のようになります ($type
フィールドに注意してください):
{ "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib", "$values": [ { "$id": "1", "$type": "MyAssembly.ClassA, MyAssembly", "Email": "[email'\u00a0protected]" }, { "$id": "2", "$type": "MyAssembly.ClassB, MyAssembly", "Email": "[email'\u00a0protected]" } ] }
IEnumerable<BaseType>
オブジェクトを使用して、JSON 文字列を settings
に逆シリアル化します。IEnumerable<BaseType> deserialized = JsonConvert.DeserializeObject<IEnumerable<BaseType>>(strJson, settings);
関連ドキュメント:
以上がNewtonsoft.Json.NET を使用して JSON を IEnumerable に逆シリアル化する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。