On Fri, Nov 17, 2017 at 5:00 AM, Bojan Tomic <[email protected]> wrote:
> Disclosure: I've posted this same question to StackOverflow. If
> cross-posting here is frowned upon, I'm sorry.
>
> For external reasons, all java Maps 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 value retrieval, as there's no way to check the type
> is actually sensible. Is there a way to get around this?

Full type information is not passed during deserialization time
because it will never change: it is instead passed
during construction and contextualization (`createContextual()` if
deserializer implement `ContextualDeserializer`).

If you need access to that type information you will need to use
custom `Module` instead of `SimpleModule`,
and override appropriate method of `Deserializers` interface (which
Module will register -- it is basically a
callback that databind calls to find custom deserializers with all
relevant configuration).

Alternatively you can implement `ContextualDeserializer`, and access
type via `BeanProperty` that is passed.

It is possible you could get `Converter` based approach to work as
well, but it too passes type information
as part of construction/configuration step and not during deserialization.

-+ Tatu +-

-- 
You received this message because you are subscribed to the Google Groups 
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to