一尘不染

杰克逊+建造者模式?

json

我希望Jackson用以下构造函数反序列化一个类:

public Clinic(String name, Address address)

反序列化第一个参数很容易。问题在于地址定义为:

public class Address {
  private Address(Map<LocationType, String> components)
  ...

  public static class Builder {
    public Builder setCity(String value);
    public Builder setCountry(String value);
    public Address create();
  }
}

并构造如下: new Address.Builder().setCity("foo").setCountry("bar").create();

有没有办法从Jackson那里获取键值对,以便自己构造地址?另外,有没有办法让Jackson来使用Builder类本身?


阅读 228

收藏
2020-07-27

共1个答案

一尘不染

只要您使用的是Jackson
2+,现在就已经内置了对此的支持

首先,您需要将此注释添加到您的Address类中:

@JsonDeserialize(builder = Address.Builder.class)

然后,您需要将此注释添加到您的Builder类中:

@JsonPOJOBuilder(buildMethodName = "create", withPrefix = "set")

如果您想重命名要构建的Builder的create方法,并且要以而不是set作为前缀的Builder的setter,则可以跳过第二个注释。

完整示例:

@JsonDeserialize(builder = Address.Builder.class)
public class Address
{
  private Address(Map<LocationType, String> components)
  ...

  @JsonPOJOBuilder(buildMethodName = "create", withPrefix = "set")
  public static class Builder
  {
    public Builder setCity(String value);
    public Builder setCountry(String value);
    public Address create();
  }
}
2020-07-27