我无法弄清楚我做错了什么。我正在尝试反序列化具有多态对象的 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。路径....”
我是否以正确的方式处理这个问题?