Jackson + Builder Pattern?(杰克逊 + 建设者模式?)
问题描述
我希望 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();
}
}
这篇关于杰克逊 + 建设者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:杰克逊 + 建设者模式?
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01