问题描述
我希望 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();
}
}
这篇关于杰克逊 + 建设者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!