我想反序列化一个Dictionary<string, AbstractDataObject>
。AbstractDataObject
是SomeClass1
和SomeClass2
继承的抽象类。字典的键值(字符串)是类的名称:
{
"StoredData": {
"SomeClass1": {
"Foo": "Test"
},
"SomeClass2": {
"Bar": 123
}
}
}
类看起来如下(简化):
public class Data
{
public Dictionary<string, AbstractDataObject> StoredData { get; set; }
}
public abstract class AbstractDataObject
{
}
public class SomeClass1 : AbstractDataObject
{
public string Foo { get; set; }
}
public class SomeClass2 : AbstractDataObject
{
public int Bar { get; set; }
}
如何告诉Json。. NET推断基于字典键的类类型?我已经环顾四周,但我不确定从哪里开始实现这个功能
你可以自定义一个JsonConverter
来处理这个:
public class CustomDictionaryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, AbstractDataObject>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var dict = new Dictionary<string, AbstractDataObject>();
JObject jo = JObject.Load(reader);
foreach (JProperty prop in jo.Properties())
{
switch (prop.Name)
{
case "SomeClass1":
dict.Add("SomeClass1", prop.Value.ToObject<SomeClass1>(serializer));
break;
case "SomeClass2":
dict.Add("SomeClass2", prop.Value.ToObject<SomeClass2>(serializer));
break;
}
}
return dict;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后像这样使用:
Data data = JsonConvert.DeserializeObject<Data>(json, new CustomDictionaryConverter());
小提琴:https://dotnetfiddle.net/ba4wB6