问题
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 Entity2
s 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