c# JsonConverter deserialize Json containing Polymorphic Object

745 views Asked by At

I can't figure out what I am doing wrong. I am trying to deserialize a JSON that has a polymorphic object. Here is my basic classes and set up

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}
   ...
}

In my AccountConverter.cs I created a ReadJson method like so

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

I call my deserializeObject in my response method like

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

I keep on getting errors on the first line in the ReadJson method. "Error reading JObject from JsonReader. Current JsonReader item is not an object. StartArray. Path...."

Am I even going about this in the right way??

0

There are 0 answers