Home > Back-end >  Moshi can't deserialize Map with List of values, returns LinkedHashTreeMap instead of value
Moshi can't deserialize Map with List of values, returns LinkedHashTreeMap instead of value

Time:02-05

Can't deserialize json to this structure: Map<String, List<SomeClass>>

I can deserialize to Map<String, SomeClass> like this:

ParameterizedType type = Types.newParameterizedType(Map.class, String.class, SomeClass.class);
JsonAdapter<Map<String, SomeClass>> adapter = moshi.adapter(type);

But when there are two collections nested, for example, Map<String, List<SomeClass>>, the next code

ParameterizedType type = Types.newParameterizedType(Map.class, String.class, List.class, SomeClass.class);
JsonAdapter<Map<String, List<SomeClass>>> adapter = moshi.adapter(type);

returns Map<String, List<LinkedHashTreeMap>>, LinkedHashTreeMap has properties of SomeClass as keys and their values as values, and "type"="SomeClass".

How can I solve this, so that deserialization runs okay, as in the first example?

CodePudding user response:

It seems that to deserialize nested collections we have to pass nested parametrized types to the adapter. After changing this

ParameterizedType type = Types.newParameterizedType(Map.class, String.class, List.class, baseType);

to this

ParameterizedType type = Types.newParameterizedType(Map.class, String.class, Types.newParameterizedType(List.class, baseType));

I now have a working solution - I get a Map with List<SomeClass> values not LinkedHashTreeMaps.

  • Related