Any deserialization from JSON in Java with Gson looks like this
public <T> T fromJson(String json, Type typeOfT)
or
public <T> T fromJson(String json, Class<T> classOfT)
For deserialization from JSON to Map I would use the second one.
Let’s say we have String json
{
"123": {
"username": "admin",
"password": "TopSecret"
},
"124": {
"username": "user",
"password": "Secret"
},
"125": {
"username": "guest",
"password": "123456"
}
}
which represent Map<String, User>
where User
is
class User {
private String username;
private String password;
...
}
Then the Java code for deserialization from JSON to Map with Gson will look like this
Type mapType = new TypeToken<Map<String, User>>() {}.getType();
Map<String, User> map= new Gson().fromJson(json, mapType);
You may also find these posts interesting: