For external reasons, all java Map
s in my system can only be received as lists of key-value pairs from the clients, e.g. a Map<String, Book>
will actually be received as Json-serialized List<MapEntry<String, Book>>
. This means I need to customize my Json deserialization process to expect this representation of maps.
The problem is that JsonDeserializer
makes me implement
deserialize(JsonParser p, DeserializationContext ctxt)
method which has no access to the detected generic type it's supposed to deserialize (Map<String, Book>
in the example above). Without that info, I can't in turn deserialize List<MapEntry<String, Book>>
without loosing type safety.
I was looking at Converter but it gives even less context.
E.g.
public Map<K,V> convert(List<MapToListTypeAdapter.MapEntry<K,V>> list) {
Map<K,V> x = new HashMap<>();
list.forEach(entry -> x.put(entry.getKey(), entry.getValue()));
return x;
}
But this will potentially create dangerous maps that will throw a ClassCastException
on retrieval, as there's no way to check the type is actually sensible.
Is there a way to get around this?
As an example of what I'd expect, Gson's JsonDeserializer
looks like this:
T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
I.e. it gives access to the expected type in a sane way.