Jackson 如何使用自定义 getter/setter 序列化地图?
我在 jackson 中有一个 bean,它使用 @JSonAnySetter 方法将所有未知参数存储在地图中。
@JSonAnySetter
handleUnkowns(String k, Object v)
{
myMap.put(k,v);
}
我使用它作为所有数据类型的“Base bean”,这样如果数据丢失,未知的参数就会被填充并且数据不会丢失......而不是杰克逊崩溃。
但是,我希望这些未知数的序列化形式不要嵌套 - 也就是说 - 当对象被序列化时,我希望序列化参数位于对象的顶层。此外,我希望自定义字段也被序列化:
//I want this map to be serialized/deserialized : {"collarWidth":10 "name":"fido"}
class Dog extens JSonBean
{
int collarWidth=0;
getCollarWidth(){return collarWidth;}
setCollarWidth(int x){collarWidth=x;}
}
请注意,在上面的情况下 - 由于我从 Map 扩展,Jackson 的自定义 Map 序列化将会发生,并且unknownParameters 将是我的 json 中的“字段”。
因此预期的 JSON 序列化将是
{"collarWidth":10 "unknownParameters":{"name":"fido"}}
而不是
{"collarWidth":10 "name":"fido"}
那么 - “合并”未知参数的最简单方法是什么与已知的,以便 java bean 序列化器保留与输入字符串相同的嵌套?
明显的解决方案是将“myMap”对象中的参数与序列化的 map 合并,但这似乎有点矫枉过正,我认为这个问题可能有一个更优雅的解决方案。
I have a bean in jackson which uses the @JSonAnySetter method to store all unknown parameters in a map.
@JSonAnySetter
handleUnkowns(String k, Object v)
{
myMap.put(k,v);
}
I use this as the "Base bean" for all my data types, so that if data is missing, the unknown parameters are populated and data is not lost.... rather than jackson crashing.
However, I want the serialized form of these unknowns to NOT be nested - that is - I want serialized parameters to be at the top level of the object, when the object is serialized. Additionally, I want the custom fields to also be serialized :
//I want this map to be serialized/deserialized : {"collarWidth":10 "name":"fido"}
class Dog extens JSonBean
{
int collarWidth=0;
getCollarWidth(){return collarWidth;}
setCollarWidth(int x){collarWidth=x;}
}
Note that in the above case - since I extend from a Map, Jackson's custom Map serialization will take place, and the unknownParameters will be a "field" in my json.
Thus the expected JSON serialization would be
{"collarWidth":10 "unknownParameters":{"name":"fido"}}
rather than
{"collarWidth":10 "name":"fido"}
So - what is the simplest way to "merge" the unknown parameters with the known ones, so that the java bean serializer retains the same nesting as the input string ?
The obvious solution is to merge the parameters from the "myMap" object with the serialized map , but that seems like overkill, and i assume that this problem might have a more elegant solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您检查过
@JsonAnyGetter
注释吗?该方法返回的映射将被展开,以使其与 @JsonAnySetter 一起使用。 此博客条目解释了用法。Have you checked out
@JsonAnyGetter
annotation? Map that method returns will be unwrapped, to make it work with@JsonAnySetter
. This blog entry explains usage.