gpt4 book ai didi

c# - JSON 根据字典键推断类类型

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:24 24 4
gpt4 key购买 nike

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

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

最佳答案

你可以制作一个自定义的 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());

fiddle :https://dotnetfiddle.net/ba4wB6

关于c# - JSON 根据字典键推断类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39215647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com