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>
?
I agree with @skaffman's response. But if you could not easily change inheritance structure drastically, there may be ways around this.
One possibility is that if you do have an interface that defines getters/setters, you could add
@JsonSerialize(as=MyInterface.class)
@JsonDeserialize(as=MyInterface.class)
which would force Jackson to only use whatever is available via specific interface.
Custom serializers/deserializers are also a possibility, but that's quite a bit of work.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With