Skip to main content
 首页 » 编程设计

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

2024年02月06日22findumars

我想将 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# 对象(列表/数组)。每个项目都应实例化为子类(Wheel 或 Break),但由于 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());