java - 如何通过多个属性使用子类型将 JSON 反序列化为类?

标签 java jackson

我有以下 JSON:

{
  "type": "cat",
  "subType": "flufy",
   ...
}

我有以下类(class):

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        ...
})
public abstract class Animal {
    public AnimalType type;
    public AnimalSubType subType;
    public String name;
}

public class Cat extends Animal {
}

public class FlufyAnimal extends Animal {
}

并且我需要在以下条件下反序列化 JSON: - 如果type等于cat并且subType等于flufy必须将JSON反序列化为FlufyAnimal类,如果type等于dog有反序列化为 Dog 类。 我该怎么做?

最佳答案

简单来说,它必须看起来像这样:

public class AnimalDesiarializer extends JsonDeserializer<Animal> {

  @Override
  public Animal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
      throws IOException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    String type = node.get("type").asText();
    String subType = node.get("subType").asText();
    if (Objects.equals(type, "cat") && Objects.equals(subType, "FlufyAnimal")) {
      return new Cat(type, subType);
    } else {
      return new Dog(type, subType);
    }
  }
}

但是您必须注意,根据您的模型,并非所有 FluffyAnimal 都是猫)

关于java - 如何通过多个属性使用子类型将 JSON 反序列化为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58916577/

相关文章:

jackson - 性能差异 - Jackson ObjctMapper.writeValue(writer, val) 与 ObjectMapper.writeValueAsString(val)

Java Jackson 解析动态 JSON 对象

java - 字符串比较 - Android

java - 使用 Post 请求在 HTTP 客户端中启用 TLS

java - JSON : Unrecognized field "value" (<objectClass>), 未标记为可忽略

java - Jackson json序列化list-of-list的特定属性值

Java 将字符串拆分为 Double[ ]

java - 使用 TCP 的 Ehcache Jgroups 复制在具有 2 节点集群的 AWS 云中不起作用

java - 将字符串分成两部分

java - Json 使用 Jackson ObjectMapper 和 spring-session 将最终类序列化到 Redis 中