我有个POJO
class Product {
String name;
Size size;
} 因此,我想将反序列化JSON映射到我的POJO。如果我在我的JSON中同时拥有这两个属性,那就没有问题了。
但在我的例子中,有时候size并不是JSON的一部分。可能还有第三个属性'type‘,我将根据它来设置我的大小。我不想在我的POJO中包含“type”。有没有杰克逊的注释可以做到这一点?
发布于 2013-11-25 12:40:33
找到了一个非常简单的解决方案!
当一个JSON属性试图映射到我的POJO属性时,它只检查是否存在一个setter。
例如,如果JSON中有一个属性type,它将尝试在我的POJO中命中名为setType(obj)的方法,而不管是否存在名为type的属性。
这对我有用!我只是在这个设置器中设置了我的其他属性。
发布于 2013-11-25 11:04:50
编写自定义反序列化器:
SimpleModule module =
new SimpleModule("ProductDeserializerModule",
new Version(1, 0, 0, null));
module.addDeserializer(Product.class, new ProductJsonDeserializer());
mapper = new ObjectMapper();
mapper.registerModule(module);//.
class ProductJsonDeserializer extends JsonDeserializer<Product>
{
@Override
public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
{
// handle here if exist a third attribute 'type' and create the product
}
}更多信息在这里:http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
https://stackoverflow.com/questions/20190350
复制相似问题