C#C
C#2y ago
Elio

✅ JSON Deserialize Derived Class

Hi, i'm struggling to deserialize my object with the Newtonsoft.Json Librairy. I've a collection of Step named Steps which can be a Stepspecial or Stepnormal. I'm trying to write my JsonConverter to deserialize the collection of Step but when i try to deserialize i keep getting the stack overflow error because jObject.ToObject call back ReadJson :
public class StepConverterJSON : JsonConverter<Step>
{
    #region Properties
    public override bool CanWrite => false;
    #endregion

    #region Override Methods
    public override void WriteJson(JsonWriter writer, Step? value, JsonSerializer serializer) { throw new NotImplementedException(); }

    public override Step? ReadJson(JsonReader reader, Type objectType, Step? existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        // Load a JObject from the JsonReader
        JObject jObject = JObject.Load(reader);

        if(jObject["Message"] != null)
        {
            // Use the new serializer to deserialize the object
            StepSpecial? stepSpecial = serializer.Deserialize<StepSpecial>(reader);
            return stepSpecial;
        }
        else
        {
            StepNormal? stepNormal = jObject.ToObject<StepNormal>(serializer);
            //StepNormal? stepNormal = serializer.Deserialize<StepNormal>(reader);
            return stepNormal;
        }
    }
    #endregion
}

Any idea how to solve this and write a good ReadJson method ? i've thought about the populate method but not sure this is the good way of doing it.
Was this page helpful?