微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Jackson 不会映射到自定义的侦听器映射对象?

如何解决Jackson 不会映射到自定义的侦听器映射对象?

所以我一直在开发一个小的 LinkedHashMap 扩展类,用于我的一个项目,我在其中编辑它以在 put 方法中有一个值更改侦听器。这是我的地图类:

    static class MapWithListeners<K,V> extends LinkedHashMap<K,V> {
        private final LinkedHashMap<K,V> delegate;
        public static final String UPDATE_EVT = "update";

        public MapWithListeners() {
            this.delegate = new LinkedHashMap<>();
        }

        public MapWithListeners(LinkedHashMap<K,V> delegate) {
            this.delegate = delegate;
        }

        private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);

        public void addPropertychangelistener(Propertychangelistener listener) {
            changeSupport.addPropertychangelistener(listener);
        }

        public void removePropertychangelistener(Propertychangelistener listener) {
            changeSupport.removePropertychangelistener(listener);
        }

        protected void firePropertyChange(String propertyName,Object oldValue,Object newValue) {
            changeSupport.firePropertyChange(propertyName,oldValue,newValue);
        }

        @Override
        public V put(K var1,V var2) {
            V oldValue = delegate.put(var1,var2);
            firePropertyChange(UPDATE_EVT,oldValue == null ? null : new AbstractMap.SimpleEntry<>(var1,oldValue),new AbstractMap.SimpleEntry<>(var1,var2));
            return oldValue;
        }
    }

问题是,我试图将一个对象映射到这个映射类的一个实例:

ObjectMapper mapper = new ObjectMapper();
MapWithListeners<String,Object> map = mapper.convertValue(mainObj,new TypeReference<MapWithListeners<String,Object>>() {
        });

结果是一张空地图。我试过只用一个普通的 LinkedHashMap 来做这个,它主要按照我需要的方式工作,但它放弃了我也需要的值更改侦听器。我假设我在 MapWithListeners 类中做错了什么,但无法弄清楚那是什么。 在此先感谢您的帮助!

编辑:我发现有必要将我的静态类更改为抽象类,基本上如下: abstract class MapWithListeners<K,V> implements Map<K,V>

然后使用抽象类型映射模块配置我的映射器,例如:

SimpleModule module = new SimpleModule().addAbstractTypeMapping(Map.class,MapWithListeners.class);
mapper.registerModule(module);

然而,走到这一步会返回一个错误,在 convertValue 行被击中,它说:

java.lang.IllegalArgumentException: Cannot find a deserializer for non-concrete Map type [map type; class com.invoiceeditor.POJOEditor$MapWithListeners,[simple type,class java.lang.String] -> [simple type,class java.lang.Object]]

有什么想法吗?

解决方法

请尝试以下操作:通过构建自定义 MapType 为 Jackson 映射器提供更多类型支持。此后,您可以将其用于转换。

我已经实现了以下内容,它确实有效,并且您帖子中提到的 IllegalArgumentException 已消失:

MapType javaType = mapper.getTypeFactory().constructMapType(MapWithListeners.class,String.class,Object.class);
MapWithListeners<String,Object> map = mapper.convertValue(mainObj,javaType);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。