【发布时间】:2017-03-21 22:00:20
【问题描述】:
使用YamlDotNet,我正在尝试反序列化以下 YAML:
Collection:
- Type: TypeA
TypeAProperty: value1
- Type: TypeB
TypeBProperty: value2
Type 属性是Collection 下所有对象的必需属性。其余属性取决于类型。
这是我理想的对象模型:
public class Document
{
public IEnumerable<IBaseObject> Collection { get; set; }
}
public interface IBaseObject
{
public string Type { get; }
}
public class TypeAClass : IBaseObject
{
public string Type { get; set; }
public string TypeAProperty { get; set; }
}
public class TypeBClass : IBaseObject
{
public string Type { get; set; }
public string TypeBProperty { get; set; }
}
根据我的阅读,我认为我最好的选择是使用自定义节点反序列化器,它源自INodeDeserializer。作为概念证明,我可以这样做:
public class MyDeserializer : INodeDeserializer
{
public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
{
if (expectedType == typeof(IBaseObject))
{
Type type = typeof(TypeAClass);
value = nestedObjectDeserializer(parser, type);
return true;
}
value = null;
return false;
}
}
我现在的问题是如何在调用nestedObjectDeserializer之前动态确定要选择的Type。
使用 JSON.Net 时,我能够使用 CustomCreationConverter,将子 JSON 读入 JObject,确定我的类型,然后从 JObject 创建一个新的 JsonReader 并重新解析对象。
有没有办法让我阅读、回滚,然后重新阅读nestedObjectDeserializer?
我可以在nestedObjectDeserializer 上调用另一种对象类型,然后从中读取Type 属性,最后通过派生类型的正常YamlDotNet 解析进行吗?
【问题讨论】:
标签: c# parsing yamldotnet