杰克逊+建筑师模式? [英] 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使用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?
推荐答案
我最终使用@JsonDeserialize实现了这个如下:
I ended up implementing this using the @JsonDeserialize as follows:
@JsonDeserialize(using = JacksonDeserializer.class)
public class Address
{...}
@JsonCachable
static class JacksonDeserializer extends JsonDeserializer<Address>
{
@Override
public Address deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException
{
JsonToken token = parser.getCurrentToken();
if (token != JsonToken.START_OBJECT)
{
throw new JsonMappingException("Expected START_OBJECT: " + token, parser.getCurrentLocation());
}
token = parser.nextToken();
Builder result = new Builder();
while (token != JsonToken.END_OBJECT)
{
if (token != JsonToken.FIELD_NAME)
{
throw new JsonMappingException("Expected FIELD_NAME: " + token, parser.getCurrentLocation());
}
LocationType key = LocationType.valueOf(parser.getText());
token = parser.nextToken();
if (token != JsonToken.VALUE_STRING)
{
throw new JsonMappingException("Expected VALUE_STRING: " + token, parser.getCurrentLocation());
}
String value = parser.getText();
// Our Builder allows passing key-value pairs
// alongside the normal setter methods.
result.put(key, value);
token = parser.nextToken();
}
return result.create();
}
}
这篇关于杰克逊+建筑师模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文