Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Builder pattern with Jackson for deserializing

Requirements :

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

I am sure that jackson work based on getters and setters on the POJO. Since, I have buildder pattern, there is no point of having setters again. In this case, How can we indicate jackson to deserialize with help of Builder pattern ?

Any help would be appreciated. I tried @JsonDeserialize(builder = MyBuilder.class) and is not working.

This is required in REST jersey. I am currently jersey-media-jackson maven module for jackson marshaling and unmarshaling.

like image 273
Balaji Boggaram Ramanarayan Avatar asked Dec 10 '14 20:12

Balaji Boggaram Ramanarayan


Video Answer


1 Answers

@JsonDeserialize is the way to go, provided that you have jackson-databind on your classpath. The following snippets are copied from the 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);
  }
}

alternatively, use the @JsonPOJOBuilder if you do not like method names that have the with prefix:

@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); }
}
like image 84
matsev Avatar answered Sep 30 '22 01:09

matsev