gpt4 book ai didi

c# - 如何使用继承/多态性将 JSON 字符串解析为 C# 对象?

转载 作者:太空宇宙 更新时间:2023-11-03 21:25:29 25 4
gpt4 key购买 nike

我想将 JSON 字符串解析为可以多态的 C# 对象。

总结一下:我不想实例化根对象,但我想根据 JSON 输入实例化继承对象。

这是我使用的 C# 对象的示例:

public class Module {
public string name;
}

public class Wheel : Module {
public int amount;
public Wheel(string name, int amount) : base(name) {...}
}

public class Break : Module {
public double delay;
public Break(string name, double delay) : base(name) {...}
}

我有这个 JSON 字符串,它是一个包含两个 JSON 对象的数组:

[{
"name":"Wheel",
"amount":4
},{
"name":"Break",
"delay":1.0
}]

我想将此 JSON 字符串反序列化为 C# 对象(列表/数组)。每个项目都应实例化为子类(WheelBreak),但由于 List 项目必须位于同一分母上,因此列表类型必须是 Module 类型。

最佳答案

如果您使用 Newtonsoft JSON Library ,您可以创建一些自定义转换器,如下所示:

public class ModuleObjectConverter : JsonCreationConverter<Module>
{
protected override Module Create(Type objectType, JObject jObject)
{
// This is the important part - we can query what json properties are present
// to figure out what type of object to construct and populate
if (FieldExists("amount", jObject)) {
return new Wheel();
} else if (FieldExists("delay", jObject)) {
return new Break();
} else {
return null;
}
}

private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// We don't deal with writing JSON content, and generally Newtonsoft would make a good job of
// serializing these type of objects without having to use a custom writer anyway
}
}

// Generic converter class - could combine with above class if you're only dealing
// with one inheritance chain, but this way it's reusable
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);

public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);

// Create target object based on JObject
T target = Create(objectType, jObject);

// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);

return target;
}
}

然后在反序列化时将此助手的一个实例传递给 Newtonsoft:

var modules = JsonConvert.DeserializeObject<List<Module>>(jsonString, new ModuleObjectConverter());

关于c# - 如何使用继承/多态性将 JSON 字符串解析为 C# 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27311635/

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