使用JsonConverter将接口反序列化为其具体子类型时会出现堆栈溢出的问题。

20 浏览
0 Comments

使用JsonConverter将接口反序列化为其具体子类型时会出现堆栈溢出的问题。

JSON结构从网络传输过来的样子如下:

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

我正在尝试使用自定义的JsonConverter将它们反序列化为顶层对象。我有以下层次结构,并用自定义转换器注释接口。在客户端中,我使用`IBase`作为反序列化辅助方法的类型参数。

[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; }
}

然后是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();
        else return JObject.toObject();
   }
}

然而,似乎我遇到了堆栈溢出的问题。自定义的反序列化器似乎一遍又一遍地运行。有没有解决办法?

0