java - 用于反序列化的 Jackson 构建器模式

标签 java json jersey jackson deserialization

Requirements :

  1. Would like to use Builder pattern
  2. Jackson for deserialization
  3. Would not like to use setters

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

如有任何帮助,我们将不胜感激。我试过 @JsonDeserialize(builder = MyBuilder.class) 但没有用。

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

最佳答案

@JsonDeserialize 是要走的路,前提是您的类路径上有 jackson-databind。以下片段摘自 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); }
}

关于java - 用于反序列化的 Jackson 构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27409808/

相关文章:

java - 从多个相关的 excel 表中读取 excel 数据并转储到 java 类中

java - 在 Hibernate 中使用 SessionFactory.getCurrentSession() 时获取 Connection 对象

json - boolean 值可以/应该用引号在 json 中传递吗?

java - 同一 WAR 中的多个 JAX-RS 应用程序

json - JAX-RS/ Jersey : Change response body from Jackson JSON errors

java - 如何在java类中打开Assets文件夹中的文件

java - 如何使用 Jackson 反序列化外部 Lombok 构建器类

java - 如何从嵌套的json数据获取数组值(java android)

java - Jackson 有类似 JSON.stringify 的东西吗?

java - 启动服务器时如何更改 persistence.xml 中的 url 属性