我的@JsonCreator和MixIn注释有什么问题?

时间:2011-09-15 23:07:20

标签: java jackson

我目前正在使用jackson 1.7尝试从第三方库反序列化对象。

所以我设置我的ObjectMapper来使用我的mixIn类:

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.getDeserializationConfig().addMixInAnnotations(com.vividsolutions.jts.geom.Point.class, MixIn.class);

我的MixIn类使用 @JsonCreator 进行注释,并使用逻辑实例化 Point 对象

public class MixIn {
private static final GeometryFactory geometryFactory = GeometryFactoryFactory.getGeometryFactory();

@JsonCreator
public static Point createPoint(@JsonProperty("x")double x, @JsonProperty("y")double y) {
    return geometryFactory.createPoint(new Coordinate(x, y));
}}

但是我得到了例外

No suitable constructor found for type [simple type, class com.vividsolutions.jts.geom.Point]: can not instantiate from JSON object (need to add/enable type information?)

调试显示我的MixIn类从未被调用,我认为它需要是具体的类,但结果相同。

我做错了什么?我的配置有什么问题?

由于

3 个答案:

答案 0 :(得分:6)

问题在于假设混合用于除添加注释之外的任何其他内容。因此,在您的情况下,将添加“createPoint()”的注释,但除非目标类具有匹配的工厂方法(以添加注释),否则这将没有任何效果。 具体来说,混合不能用于注入静态工厂方法;它们只能用于将注释与现有类相关联。

答案 1 :(得分:0)

尝试使用@JsonIgnoreProperties({"isMilestoneView", "milestoneId"}) 类级别注释

答案 2 :(得分:0)

您可以使用带有自定义反序列化器的 mixin

@JsonDeserialize(using = MixIn.PointDeserializer.class)
public class MixIn {
  static class PointDeserializer extends JsonDeserializer<Point> {
    @Override
    public Point deserialize(@Nullable JsonParser p, @Nullable DeserializationContext ctxt)
      throws IOException, JsonProcessingException {
      if (p == null) {
        return null;
      }
      TreeNode t = p.readValueAsTree();
      x = t.get("x");
      y = t.get("y");
      return createPoint(x,y);
    }
  }

  private static final GeometryFactory geometryFactory = GeometryFactoryFactory.getGeometryFactory();
  public static Point createPoint(@JsonProperty("x")double x, @JsonProperty("y")double y){
    return geometryFactory.createPoint(new Coordinate(x, y));
  }
}
相关问题