0

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??

justKeepCodin
  • 117
  • 2
  • 11
  • Please add json example. – Genusatplay Apr 17 '21 at 00:54
  • 1
    But error say you get array, not `JObject` in reader, mb `JArray.Load(reader)` – Genusatplay Apr 17 '21 at 00:57
  • 1
    Take a look at the converter from [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182),it does what you want. – dbc Apr 17 '21 at 01:08
  • 2
    Oh I see you need to use `[JsonProperty(ItemConverterType = typeOf(AccountConverter)]` instead of `[JsonConverter(typeOf(AccountConverter)]` because your converter applies to the list items, not the list itself. See [Deserializing a list of interfaces with a custom JsonConverter?](https://stackoverflow.com/a/40979963/3744182). In fact this looks to be a duplicate, agree? – dbc Apr 17 '21 at 01:11
  • @dbc the [JsonProperty(ItemConverterType = typeOf(AccountConverter)] got the Json to deserialize with no errors. I can see the Json Keys now in my object. Only weird thing is the values for them are all coming back as null. But thats a different issue and it seems this issue is solved. Thank you – justKeepCodin Apr 17 '21 at 01:25

0 Answers0