猿问

避免继承 JsonConverter 递归

所以我有一个我点击的 API,以便在数据库中获取有关动物的详细信息


这些动物有 ID,所以我的网络请求看起来像这样/animal/1234


API 的响应如下所示:


{

  "name": "Tony",

  "type": "Tiger",

  "stripeCount": 14

}

或者替代地


{

  "name": "Kermit",

  "type": "Frog",

  "slimy": true

}

当我查询 API 时,我不知道type我会返回什么动物,但在某些情况下,我想将它们反序列化为适合它们的类type


这是我目前正在使用的类,包括JsonConverter我正在尝试使用的属性:


[JsonConverter(typeof(AnimalJsonConverter))]

class Animal {

  public string name { get; set; }

  public string type { get; set; }

}


class Tiger : Animal {

  public int stripeCount { get; set; }

}

我已经设置了一个JsonConverter<Animal>实现方法的方法ReadJson,如下所示:


public override Animal ReadJson(JsonReader reader, Type objectType, Post existingValue, bool hasExistingValue, JsonSerializer serializer) {

  var animalObj = JObject.Load(reader);

  var type = (string)animalObj["type"];


  switch(type) {

    case "Tiger":

      return animalObj.ToObject<Tiger>();

    default:

      return animalObj.ToObject<Animal>();

  }

}

然而,这会导致问题,因为该语句animalObj.ToObject<Tiger>();尊重JsonConverteronAnimal并尝试ReadJson再次调用我的方法,从而导致递归地狱


如果有人能看到这个问题的解决方案,我将不胜感激


白猪掌柜的
浏览 92回答 1
1回答

largeQ

您可以使用不同的策略 - 填充类型的实例:class AnimalJsonConverter : JsonConverter<Animal>{&nbsp; &nbsp; public override void WriteJson(JsonWriter writer, Animal value,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JsonSerializer serializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new NotImplementedException();&nbsp; &nbsp; }&nbsp; &nbsp; public override Animal ReadJson(JsonReader reader, Type objectType,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Animal existingValue, bool hasExistingValue, JsonSerializer serializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var animalObj = JObject.Load(reader);&nbsp; &nbsp; &nbsp; &nbsp; var type = (string)animalObj["type"];&nbsp; &nbsp; &nbsp; &nbsp; Animal instance;&nbsp; &nbsp; &nbsp; &nbsp; switch (type)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "Tiger":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instance = new Tiger();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "Frog":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instance = new Frog();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instance = new Animal();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; serializer.Populate(animalObj.CreateReader(), instance);&nbsp; &nbsp; &nbsp; &nbsp; return instance;&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答