【问题标题】:what is wrong with my @JsonCreator and MixIn annotation?我的 @JsonCreator 和 MixIn 注释有什么问题?
【发布时间】:2011-09-15 23:07:19
【问题描述】:

我目前正在使用 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 类从未被调用,我认为它需要是具体的类但结果相同。

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

谢谢

【问题讨论】:

    标签: java jackson


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,这很有意义,我想我唯一的选择是序列化所有其他所需的属性(大约3个更复杂的对象:()用于目标类构造函数并在 MixIn 类中使用它们。对吗?
    • 再次感谢,我终于在反序列化时结束了排除该字段,因为它不再需要了。
    • 拥有这个或类似的东西,对于轻松反序列化无法修改的类将非常有帮助。有很多情况是一般的反序列化太难了。
    • @loesak 对于静态工厂方法的特定情况,这确实很有用。您可能想在 github issue tracker 提交 RFE 并提出改进建议。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以使用带有自定义反序列化器的 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));
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-18
        • 2013-06-10
        • 1970-01-01
        • 2015-10-12
        • 2015-08-10
        • 1970-01-01
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多