杰克逊 - 序列化时忽略地图超类 [英] Jackson - ignore Map superclass when serializing

查看:125
本文介绍了杰克逊 - 序列化时忽略地图超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些扩展 LinkedHashMap< String,Object> 的模型类:它们定义了包含Map的get和put方法的getter和setter。我试图使用Jackson(使用RESTEasy)序列化这些类的实例,但是Jackson拒绝注意我的getter,它们被注释为 @JsonProperty 。相反,它只是序列化背景映射的键值对。我尝试使用 @JsonAutoDetect 禁用所有方法和字段的自动检测,但没有改变任何东西。有没有办法阻止杰克逊自动序列化地图,或者必须创建不扩展的新模型类LinkedHashMap< String,Object>

I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods. I am trying to serialize instances of these classes using Jackson (with RESTEasy), but Jackson refuses to pay attention to my getters, which are annotated with @JsonProperty. Instead, it is only serializing the key-value pairs of the backing map. I tried using @JsonAutoDetect to disable auto-detection for all methods and fields, but that didn't change anything. Is there a way to prevent Jackson from automatically serializing a Map, or must I create new model classes that don't extend LinkedHashMap<String, Object>?

推荐答案


我有几个模型类可以扩展 LinkedHashMap< String,Object> :它们定义了getter和setter,它包装了Map的get和put方法。

I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods

这是一个典型的例子, >不使用继承:你发现一些其他代码片段(即Jackson)正在将你的类视为一个超类的实例,这不是你想要的。在这种情况下(通常情况下),通常最好使用组合而不是继承。

This is a classic example of when not to use inheritance: you're finding that some other piece of code (i.e. Jackson) is treating your class like an instance of its superclass, which isn't what you want it to do. In cases like these (and also in general), it's usually better to use composition rather than inheritance.

我建议您将模型类重写为包含一个地图,而不是扩展一个。你得到的控制比方法更多,结果模型不那么脆弱。如果您需要将模型查看为 Map ,则执行一个 asMap 方法(或类似的方法)视图。

I recommend rewriting your model class to contain a map, rather than extending one. You get much more control than way, and the resulting model is less brittle. If you need to view your model as a Map, then implement an asMap method (or something similar) which renders that view.

这篇关于杰克逊 - 序列化时忽略地图超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆