Bypass runtime type erasure for generic map serializer

﹥>﹥吖頭↗ 提交于 2019-12-11 06:05:24

问题


I'm working on a serializer for a Map<K,V> which serializes map entries as JSON array of objects with key and value being able to contain arbitrary types (including complex types for keys). I have

public class MapEntryDeserializer<K,V> extends StdDeserializer<Map<K,V>> {
    private static final long serialVersionUID = 1L;

    public MapEntryDeserializer(Class<Map<K,V>> vc) {
        super(vc);
    }

    public MapEntryDeserializer(JavaType valueType) {
        super(valueType);
    }

    @Override
    public Map<K, V> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Map<K,V> retValue = new HashMap<>();
        List<Entry<K,V>> entries = p.readValueAs(new TypeReference<List<Entry<K,V>>>() {});
        for(Entry<K,V> entry : entries) {
            retValue.put(entry.getKey(),
                    entry.getValue());
        }
        return retValue;
    }

    private static class Entry<K,V> {
        private K key;
        private V value;

        public Entry() {
        }

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }
    }
}

which is working except for the new TypeReference<List<Entry<K,V>>> which resolves to List<Entry<Object, Object>> at runtime and thus nested Entity2s to be deserialized as Map.

{
  "id" : 1,
  "valueMap" : [ {
    "key" : {
      "type" : "richtercloud.jackson.map.custom.serializer.Entity2",
      "id" : 2
    },
    "value" : 10
  } ]
}

So, I'm wondering whether there's a way to achieve a generic solution, e.g. pass Class<? extends K> and Class<? extends V> and construct a JavaType with TypeFactory.constructParametricType.

I'm using Jackson 2.9.4.

来源:https://stackoverflow.com/questions/49213606/bypass-runtime-type-erasure-for-generic-map-serializer

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