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

问题描述

我不知道我做错了什么。我正在尝试反序列化具有多态对象的 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}
   ...
}

在我的 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()
    };
}

我在我的响应方法中调用我的 deserializeObject 就像

JsonConvert.DerserializeObject<Information>(result,JsonConverterSettings.Settings)

我一直在 ReadJson 方法的第一行出现错误。 “从 JsonReader 读取 JObject 时出错。当前的 JsonReader 项不是对象。StartArray。Path ....”

我的做法是否正确?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)