0

I have a Json like this:

{
    "a": [
        {"name": "a"}
    ],
    "b": [
        {"name": "b"}
    ]
} 

And i use Retrofit for convert to java object like this:

public interface TheService {
    @GET("data")
    Call<HashMap<String, ArrayList<User>>> getUsers();
}

It's work fine. But when i cache my json string and parse it manually with Gson:

Gson gson = new Gson();
HashMap<String, ArrayList<User>> map = gson.fromJson(jsonString, HashMap.class);

It throws error: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xxx.User

So how can i covert jsonString to HashMap<String, ArrayList<User>> object with Gson?

MarsPeople
  • 1,772
  • 18
  • 30
  • 1
    Hope this one helps. https://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson – vinv Apr 26 '20 at 00:07
  • I found solution here with TypeToken: https://stackoverflow.com/a/32494079/1472483 – MarsPeople Apr 26 '20 at 19:17

1 Answers1

0

I found a solution here: (Detailed explain) https://stackoverflow.com/a/32494079/1472483

With using TypeToken

Type type = new TypeToken<HashMap<String, ArrayList<User>>>() {}.getType();
HashMap<String, ArrayList<User>> map = gson.fromJson(jsonString, type);
MarsPeople
  • 1,772
  • 18
  • 30