简体   繁体   English

将JSON反序列化为C#集合

[英]Deserialize JSON to C# collection

I am using Newtonsoft.Json to serialize/deserialize my C# object to/from JSON. 我正在使用Newtonsoft.Json将C#对象与JSON序列化/反序列化。 My C# object has a property of following type: 我的C#对象具有以下类型的属性:

List<BaseClass> objects { get; set; }

This collection holds different child objects (eg - ChildClass1, ChildClass2). 该集合包含不同的子对象(例如-ChildClass1,ChildClass2)。

Serializing to JSON works fine but while deserializing it creates objects of BaseClass in collection (which is obvious :)). 序列化为JSON可以正常工作,但是反序列化时会在集合中创建BaseClass对象(这很明显:))。

Is there a way I can create concrete child objects while deserializing? 反序列化时,有什么方法可以创建具体的子对象吗? I tried creating a custom converter by implementing CustomCreationConverter<BaseClass> . 我尝试通过实现CustomCreationConverter<BaseClass>创建一个自定义转换器。 But the problem is overridden Create method gives me just the type and based on that I cannot decide which object to return (ChildClass1 or ChildClass2) 但是问题却被覆盖了。Create方法只给我提供类型,因此无法确定要返回哪个对象(ChildClass1或ChildClass2)。

My JSON string has a Type property by which I can identify the child object to create. 我的JSON字符串具有Type属性,通过它可以标识要创建的子对象。

Any help is highly appreciated. 非常感谢您的帮助。

You can use the TypeNameHandling option: 您可以使用TypeNameHandling选项:

var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }

JsonConvert.SerializeObject(myObject, Formatting.Indented, settings );

The TypeNameHandling option "Auto" ensures that type names are included in the serialized JSON for subclasses. TypeNameHandling选项“自动”可确保类型名称包含在子类的序列化JSON中。 But watch out: these names become invalid when the classes or their namespaces are renamed! 但请注意:重命名类或其名称空间后,这些名称将无效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM