我有一个 POJO
class Product {
String name;
Size size;
}
所以,我想将一个反序列化的 JSON 映射到我的 POJO。如果我的 JSON 中有这两个属性,那不是问题。
但就我而言,有时大小不会成为 JSON 的一部分。可能有第三个属性“类型”,我将根据它来设置我的尺寸。我不想在我的 POJO 中包含“类型”。有没有 jackson 注释可以做到这一点?
最佳答案
编写自定义反序列化器:
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
关于java - 使用 Jackson 的自定义 JSON 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20190350/