0

The json structures come over from network like this:

{
  type: "a",
  specialPropA: "propA"
}
{
  type: "b",
  specialPropB: 1
}

I am trying to deserialize them as top level objects with a custom JsonConverter. I have the following hierarchy and annotate the interface with a custom converter. In the client I use IBase as a type paratemer for the a deserializer helper method.

[JsonConverter(typeof(MyJsonConverter))]
public interface IBase 
{
  string type { get; }
}
public class DerivedA : IBase
{
  string type => "A";

  string specialPropA { get; set; }
}
public class DerivedB : IBase
{
  string type => "B";

  int specialPropB { get; set; }
}

Then the implementation of the JsonConverter.

public class MyJsonConverter
{
   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
        JObject jsonObject = JObject.Load(reader);
        if (type == 'A') return JObject.toObject<DerivedA>();
        else return JObject.toObject<DerivedB>();
   }
}

However, it seems that I get stack overflow. The custom deseriazer seems to run over and over again. Is there a work-around?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
ChinPaagn
  • 1
  • 1
  • The answers from [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182) solve this problem by allocating the concrete object manually and then using `serializer.Populate(jObject.CreateReader(), newObject);`. You can also disable the base class converter on derived classes as shown in [How to call JsonConvert.DeserializeObject and disable a JsonConverter applied to a base type via `[JsonConverter]`?](https://stackoverflow.com/q/45547123/3744182). – dbc Jan 12 '21 at 05:12
  • 1
    @dbc thanks, that is what I need. – ChinPaagn Jan 12 '21 at 15:33

0 Answers0