gpt4 book ai didi

c# - 将 JSON 反序列化为子类

转载 作者:太空狗 更新时间:2023-10-30 00:25:22 25 4
gpt4 key购买 nike

我有 3 个类:

class Person {
public bool IsFemale { get; set; }
}

class Female : Person {
public string FemaleSpecificProperty { get; set; }
}

class Male: Person {
public string MaleSpecificProperty { get; set; }
}

如何根据 Female 的值将给定的 JSON 字符串反序列化为特定实例(MalePerson.IsFemale)属性(property)? (预先我不知道使用了哪种确切类型,该属性是唯一的指示)

我看着雇用 CustomCreationConverter<T>但不知道如何让它在这里工作。

最佳答案

这里是你的 person 类的转换器。它获取 IsFemale 字段值,并基于它创建 FemaleMale 人,由序列化程序填充:

public class PersonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Person).IsAssignableFrom(objectType);
}

public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
var isFemale = (bool)jObject["IsFemale"];
Person target = isFemale ? (Person)new Female() : new Male();
serializer.Populate(jObject.CreateReader(), target);
return target;
}

public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

用法:

List<Person> people = new List<Person>
{
new Male { IsFemale = false, MaleSpecificProperty = "Y" },
new Male { IsFemale = false, MaleSpecificProperty = "Y" },
new Female { IsFemale = true, FemaleSpecificProperty = "X" }
};

string json = JsonConvert.SerializeObject(people);
var result =
JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());

另请查看 alex 提出的问题:How to implement custom JsonConverter

关于c# - 将 JSON 反序列化为子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17500453/

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