【问题标题】:Builder pattern with Jackson for deserializing用于反序列化的 Jackson 构建器模式
【发布时间】:2015-02-09 04:00:29
【问题描述】:

要求:

  1. 希望使用 Builder 模式
  2. Jackson 用于反序列化
  3. 不想使用二传手

我确信 jackson 基于 POJO 上的 getter 和 setter 工作。因为,我有建造者模式,所以没有必要再有二传手。在这种情况下,我们如何指示杰克逊在 Builder 模式的帮助下反序列化?

任何帮助将不胜感激。我试过 @JsonDeserialize(builder = MyBuilder.class) 并没有工作。

这在 REST jersey 中是必需的。我目前是用于杰克逊编组和解组的 jersey-media-jackson maven 模块。

【问题讨论】:

    标签: java json jersey jackson deserialization


    【解决方案1】:

    @JsonDeserialize 是可行的方法,前提是您的类路径中有 jackson-databind。以下sn-ps复制自Jackson Documentation

    @JsonDeserialize(builder=ValueBuilder.class)
    public class Value {
      private final int x, y;
      protected Value(int x, int y) {
        this.x = x;
        this.y = y;
      }
    }
    
    public class ValueBuilder {
      private int x, y;
    
      // can use @JsonCreator to use non-default ctor, inject values etc
      public ValueBuilder() { }
    
      // if name is "withXxx", works as is: otherwise use @JsonProperty("x") or @JsonSetter("x")!
      public ValueBuilder withX(int x) {
        this.x = x;
        return this; // or, construct new instance, return that
      }
      public ValueBuilder withY(int y) {
        this.y = y;
        return this;
      }
    
      public Value build() {
        return new Value(x, y);
      }
    }
    

    或者,如果您不喜欢带有 with 前缀的方法名称,请使用 @JsonPOJOBuilder

    @JsonPOJOBuilder(buildMethodName="create", withPrefix="con")
    public class ValueBuilder {
      private int x, y;
    
      public ValueBuilder conX(int x) {
        this.x = x;
        return this; // or, construct new instance, return that
      }
      public ValueBuilder conY(int y) {
        this.y = y;
        return this;
      }
    
      public Value create() { return new Value(x, y); }
    }
    

    【讨论】:

    • 我发现了问题。 @JsonPOJOBuilder 将始终假定设置器将以“with”开头,为了克服这一点,我使用了空前缀。 (withPrefix="") 解决了我的问题。感谢您的指点。
    • 我没有仔细阅读,我遇到了由于我的项目中没有 jackson-databind 依赖而导致的大量问题。当心。
    • 我读到第二个块(“替代,只是@JsonPOJOBuilder”)意味着我可以这样做代替,而不是除了 @JsonDeserialize 注释。至少对我来说,我需要两个注释。
    猜你喜欢
    • 2019-01-31
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多