JSON根据Dictionary键推断类类型

时间:2016-08-29 21:42:14

标签: c# json dictionary serialization json.net

我想反序列化Dictionary<string, AbstractDataObject>AbstractDataObjectSomeClass1SomeClass2继承的抽象类。字典的键值(字符串)是类的名称:

{
  "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基于Dictionary键推断类类型?我环顾四周,但我不确定从哪里开始实现此功能

1 个答案:

答案 0 :(得分:1)

您可以自定义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