我有一个POJO
class Product {
String name;
Size size;
}
所以,我想将一个反序列化的JSON映射到我的POJO。如果我在JSON中同时具有这两个属性,那么这不是问题。
但就我而言,有时大小不会成为JSON的一部分。可能存在第三个属性'type',我将根据该属性设置我的大小。我不想在我的POJO中包含'type'。杰克逊有没有注释可以做到这一点?
答案 0 :(得分:3)
编写自定义反序列化程序:
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
答案 1 :(得分:1)
为此找到了一个非常简单的解决方案!
当尝试将JSON属性映射到我的POJO属性时,它只检查是否存在setter。
例如,如果JSON中存在属性type
,它将尝试在我的POJO中命中名为setType(obj)
的方法,而不管是否存在名为type
的属性。
这对我有用!我只是在这个setter中设置了我的其他属性。