Jackson - ignore Map superclass when serializing

痴心易碎 提交于 2019-11-29 07:33:26

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.

StaxMan

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.

You can implement your own org.codehaus.jackson.map.DeserializerProvider which extends Jackson's org.codehaus.jackson.map.deser.StdDeserializerProvider and overwrite method _createDeserializer:

import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.codehaus.jackson.map.DeserializationConfig;
...

class MyDeserializerProvider extends StdDeserializerProvider {

    @Override
    protected JsonDeserializer<Object> _createDeserializer(DeserializationConfig config, JavaType type, BeanProperty property) throws JsonMappingException {
        if (type.isMapLikeType()) {       // (1)
            return this._factory.createBeanDeserializer(config, this, type, property);
        } else {
            return super._createDeserializer(config, type, property);
        }
    }
}

(1) use if-condition that meets your needs

The custom deserializer is registered directly at the ObjectMapper:

ObjectMapper om = new ObjectMapper();
om.setDeserializerProvider(new MyDeserializerProvider());

I tested this with Jackson 1.9.11.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!