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

Jackson deserialize polymorphic types not under my control

我想(取消)编组包含 this type 字段的对象。虽然序列化效果很好,但我无法反序列化它。 实施 classes 不在我的控制之下。我想一般来说,由于缺少构造函数和/或设置器,无法反序列化为原始实现 class。

另一方面,我想保存 json.

中包含的所有信息(作为 java 对象)

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

您可以使用 Jackson Mixins 在有问题的 class/field 上伪造一个 @JsonDeserialize(using=CustomDeserializer.class) 注释。 然后您可以尝试在给定的反序列化器 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