c#JsonConverter反序列化包含多态对象的Json

c#JsonConverter反序列化包含多态对象的Json,c#,json,polymorphism,deserialization,jsonconverter,C#,Json,Polymorphism,Deserialization,Jsonconverter,我不知道我做错了什么。我正在尝试反序列化具有多态对象的JSON。这是我的基本课程和设置 public class Information { [JsonConverter(typeOf(AccountConverter)] public list<BaseAccount> Accounts {get; set;} public decimal TotalBalance {get; set;} ... } public class BaseAccoun

我不知道我做错了什么。我正在尝试反序列化具有多态对象的JSON。这是我的基本课程和设置

public class Information
{
    [JsonConverter(typeOf(AccountConverter)]
    public list<BaseAccount> Accounts {get; set;}
    public decimal TotalBalance {get; set;}
    ...
}

public class BaseAccount
{
   public int Id {get; set;}
   public virtual AccountType Type { get;} //enum value that I base account type off of.
   ...
}

// I have a few different kinds of accounts but here is an example of one
public class BankAccount: BaseAccount
{
   public decimal value {get; set;}
   public override AccountType Type { get {return AccountType.Bank}
   ...
}
公共类信息
{
[JsonConverter(类型(AccountConverter)]
公共列表帐户{get;set;}
公共十进制总余额{get;set;}
...
}
公共类基本帐户
{
公共int Id{get;set;}
公共虚拟AccountType类型{get;}///我基于帐户类型的枚举值。
...
}
//我有几种不同的账户,但这里有一个例子
公共类银行账户:基本账户
{
公共十进制值{get;set;}
公共重写AccountType类型{get{return AccountType.Bank}
...
}
在我的AccountConverter.cs中,我创建了一个ReadJson方法,如下所示

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
    var jo = JObject.Load(reader);
    var account= jo.ToObject<BaseAccount>();
    if (account== null) throw new ArgumentOutOfRangeException();
    return account.Type switch
    {
        AccountType.Bank => jo.ToObject(typeof(BankAccount), serializer),
        ... // have multiple other account types
        _ => throw new ArgumentOutOfRangeException()
    };
}
public override object?ReadJson(JsonReader reader,objectType,object?existingValue,JsonSerializer序列化程序)
{
var jo=JObject.Load(读卡器);
var account=jo.ToObject();
如果(account==null)抛出新的ArgumentOutOfRangeException();
返回帐户。类型开关
{
AccountType.Bank=>jo.ToObject(typeof(BankAccount),序列化程序),
…//有多个其他帐户类型
_=>抛出新ArgumentOutOfRangeException()参数
};
}
我在响应方法中调用反序列化对象,如下所示

JsonConvert.DerserializeObject<Information>(result, JsonConverterSettings.Settings)
JsonConvert.DerserializeObject(结果,JsonConverterSettings.Settings)
我一直在ReadJson方法的第一行出现错误。“从JsonReader读取JObject时出错。当前JsonReader项不是一个对象。StartArray.Path…”


我这样做是否正确呢?

请添加json示例。但错误是,在reader中获取数组,而不是
JObject
,mb
JArray.Load(reader)
查看转换器,它符合您的要求。哦,我发现您需要使用
[JsonProperty(ItemConverterType=typeOf(AccountConverter)]
,而不是
[JsonConverter(typeOf(AccountConverter)]
因为您的转换器应用于列表项,而不是列表本身。请参阅。事实上,这看起来是重复的,同意吗?@dbc[JsonProperty(ItemConverterType=typeOf(AccountConverter)]让Json反序列化,没有错误。我现在可以在我的对象中看到Json键。唯一奇怪的是,它们的值都返回为null。但这是另一个问题,似乎这个问题已经解决了。谢谢