Jackson - 序列化时忽略 Map 超类 [英] Jackson - ignore Map superclass when serializing

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

问题描述

我有一些扩展 LinkedHashMap 的模型类:它们定义了封装 Map 的 get 和 put 方法的 getter 和 setter.我正在尝试使用 Jackson(使用 RESTEasy)序列化这些类的实例,但 Jackson 拒绝关注我的 getter,这些 getter 用 @JsonProperty 进行了注释.相反,它只是序列化支持映射的键值对.我尝试使用 @JsonAutoDetect 禁用所有方法和字段的自动检测,但这并没有改变任何东西.有没有办法阻止 Jackson 自动序列化 Map,或者我必须创建不扩展 LinkedHashMap 的新模型类?

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 的模型类:它们定义了封装 Map 的 get 和 put 方法的 getter 和 setter

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)将您的类视为其超类的实例,这不是't 你想让它做什么.在这种情况下(以及一般情况下),通常最好使用组合而不是继承.

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.

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

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