杰克逊反序列化不受我控制的多态类型



我想(取消)封送包含此类型字段的对象。虽然序列化效果很好,但我无法反序列化它。实现类不受我的控制。我想一般来说,由于缺少构造函数和/或setter,不可能反序列化为原始实现类。

另一方面,我想保存 json 中包含的所有信息(作为 java 对象)。

我有哪些选择来实现这一目标,是否有最佳或良好做法?

您可以使用

Jackson Mixins伪造相关类/字段的@JsonDeserialize(using=CustomDeserializer.class)注释。然后,您可以尝试在给定的反序列化程序类中自行创建实例。

// I'm not sure whether annotations (@JsonTypeInfo) on class level are supported as well to allow the polymorphistic type decision.
abstract class MixIn {
  // make constructor usable if available
  MixIn(@JsonProperty("id") int a, @JsonProperty("name") String b) { }
  @JsonDeserialize(using=CustomDeserializer.class) abstract TypeX getTypeX();
  
}

然后你可以像这样使用它

objectMapper.addMixIn(TypeXContainer.class, MixIn.class);

多克斯:http://wiki.fasterxml.com/JacksonMixInAnnotations

最新更新