本文介绍了杰克逊 + 建造者模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like Jackson to deserialize a class with the following constructor:

public Clinic(String name, Address address)

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

Deserializing the first argument is easy. The problem is that Address is defined as:

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 类本身?

Is there a way to get key-value pairs from Jackson in order to construct the Address myself? Alternatively, is there a way to get Jackson to use the Builder class itself?

推荐答案

只要你使用的是 Jackson 2+,那么现在就有内置对此表示支持.

As long as you are using Jackson 2+, then there is now built in support for this.

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

First you need to add this annotation to your Address class:

@JsonDeserialize(builder = Address.Builder.class)

然后你需要把这个注解添加到你的Builder类中:

Then you need to add this annotation to your Builder class:

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

如果您愿意将 Builder 的 create 方法重命名为 build,并且您的 Builder 的 setter 以 with 而不是 set 为前缀,则可以跳过第二个注释.

You can skip this second annotation if you are happy to rename your Builder's create method to build, and your Builder's setters to be prefixed to with, instead of set.

完整示例:

@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();
  }
}

这篇关于杰克逊 + 建造者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:45