[英]Custom JSON mapping using Jackson
I have a POJO 我有一个POJO
class Product {
String name;
Size size;
}
So, I want to map a deserialize a JSON to my POJO. 所以,我想将一个反序列化的JSON映射到我的POJO。 If I have both the attributes in my JSON, it is not a problem.
如果我在JSON中同时具有这两个属性,那么这不是问题。
But in my case, sometimes size will not be a part of the JSON. 但就我而言,有时大小不会成为JSON的一部分。 There might be a third attribute 'type' based on which I will set my size.
可能存在第三个属性'type',我将根据该属性设置我的大小。 I do not want to include 'type' in my POJO.
我不想在我的POJO中包含'type'。 Are there any Jackson annotations which can do this?
杰克逊有没有注释可以做到这一点?
write your custom Deserializers: 编写自定义反序列化程序:
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
}
}
More info here: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers 更多信息: http : //wiki.fasterxml.com/JacksonHowToCustomDeserializers
Found a pretty simple solution for this! 找到了一个非常简单的解决方案!
When a JSON attribute is attempted to be mapped to my POJO's attribute, it just checks whether a setter exists for it. 当尝试将JSON属性映射到我的POJO属性时,它只检查是否存在setter。
For example, if there is an attribute type
in JSON, it will try to hit a method named setType(obj)
in my POJO, regardless of whether there exists an attribute named type
. 例如,如果JSON中存在属性
type
,它将尝试在我的POJO中命中名为setType(obj)
的方法,而不管是否存在名为type
的属性。
This worked for me! 这对我有用! I simply set my other attributes inside this setter.
我只是在这个setter中设置了我的其他属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.