使用Jackson定制JSON映射 [英] Custom JSON mapping using Jackson
问题描述
我有一个POJO
class Product {
String name;
Size size;
}
所以,我想将一个反序列化的JSON映射到我的POJO。如果我在JSON中同时拥有这两个属性,那么这不是问题。
So, I want to map a deserialize a JSON to my POJO. If I have both the attributes in my JSON, it is not a problem.
但就我而言,有时大小不会成为JSON的一部分。可能存在第三个属性'type',我将根据该属性设置我的大小。我不想在我的POJO中加入'type'。杰克逊有没有注释可以做到这一点?
But in my case, sometimes size will not be a part of the JSON. There might be a third attribute 'type' based on which I will set my size. I do not want to include 'type' in my POJO. Are there any Jackson annotations which can do this?
推荐答案
为此找到一个非常简单的解决方案!
Found a pretty simple solution for this!
当a尝试将JSON属性映射到我的POJO属性,它只检查是否存在setter。
When a JSON attribute is attempted to be mapped to my POJO's attribute, it just checks whether a setter exists for it.
例如,如果JSON中存在属性 type
,它将尝试命中名为<$的方法c $ c>我的POJO中的setType(obj),无论是否存在名为的属性
。
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
.
这对我有用!我只是在这个setter中设置了我的其他属性。
This worked for me! I simply set my other attributes inside this setter.
这篇关于使用Jackson定制JSON映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!