1

I have the following JSON document:

{
  "1786042": {},
  "2064178": {
    "initialImportDate": "2015-11-13T12:22:53.585",
    "hideCrossedOutPrice": false,
    "salesCount": 0,
  },
  ...
}

How can I get access to the list of products, which are defined by id and not a name, that could be deserialized?

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
4ndro1d
  • 2,926
  • 7
  • 35
  • 65
  • Possible duplicate of [How can I convert JSON to a HashMap using Gson?](http://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson) – Lyubomyr Shaydariv Mar 31 '17 at 08:59

1 Answers1

1

You can use TypeToken here:

I am assuming a class named Product, which contains properties like initialImportDate, hideCrossedOutPrice etc.

Now You can use TypeToken to deserialize this json, like this:

Type productMap = new TypeToken<Map<Integer, Product> >() {}.getType();
Map<Integer, Product> result= gson.fromJson(jsonString, productMap);
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
  • I did not mention, that I am using Retrofit as well. So I have a Call like `call.enqueue(new Callback>>()` and this delivers me `Failed to invoke protected com.google.gson.reflect.TypeToken() with no args` – 4ndro1d Mar 31 '17 at 09:16
  • 2
    @4ndro1d Sachin Gupta has provided you a generic solution that is used with "vanilla" Gson when it's the only way to "write down" the actual type information. You callback must accept `Map` and not type token, because Retrofit should be able to analyze the interface method return type itself. – Lyubomyr Shaydariv Mar 31 '17 at 09:20