2

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?

wanderbild
  • 43
  • 5

1 Answers1

1

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.

wanderbild
  • 43
  • 5
  • Ah, yes. Parameterized types can be tricky. Maybe Moshi should fail with an error message when it receives a Map or similar by accident. Glad you got it working. – Eric Cochran Feb 03 '23 at 16:40