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

标签 c# json json.net

我想将 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/

相关文章:

c# - 具有长日期时间的 SQL 查询?

c# - 将相对路径转换为绝对路径

javascript - 使用map()读取Json对象

c# - 统一 3D。子对象没有改变

c# - xmlwriter 作为 xmlreader 的输入

c# - 如何将Json反序列化为对象?

json - 如何在VB6中将字符串转换或解码为可读格式?

c# - 从 ModelState 中删除 JSON.net 序列化异常

c# - 使用 C# 将 JSON 字符串从 Camel 大小写转换为 Pascal 大小写

c# - 如何模拟 JsonReader 单元测试自定义 JsonConverter