我希望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();
new Address.Builder().setCity("foo").setCountry("bar").create();
有没有办法从Jackson那里获取键值对,以便自己构造地址?另外,有没有办法让Jackson来使用Builder类本身?
只要您使用的是Jackson 2+,现在就已经内置了对此的支持。
首先,您需要将此注释添加到您的Address类中:
Address
@JsonDeserialize(builder = Address.Builder.class)
然后,您需要将此注释添加到您的Builder类中:
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(); } }