javagenericsjsonb-api

Json-Binding API fromJson method returning List<HashMap>


I am trying to deserialize a json from a file using JSON-B API

Here is the code

public List<User> getUsers(String file) {
    InputStream is = getResourceAsStream(file);
    return JsonbBuilder.create().fromJson(is, new ArrayList<User>(){}.getClass().getGenericSuperclass());
}

It works as expected.

I tried to generalize this method instead of hardcoding User, but it doesn't seem to work

public static <T> List<T> getFromSource(String file, Class<T> t) {
 InputStream is = getResourceAsStream(file);
 return getJsonb().fromJson(is, t.getGenericSuperclass());
}

Trying to call the above method

List<User> users = getFromSource("users.json", User.class);
User user = user.get(0);

But, it threw Exception in thread "main" java.lang.ClassCastException: java.util.HashMap incompatible with User So, looks like it is a List<HashMap> despite List<User>


Solution

  • In your working method the type is:

    new ArrayList<User>(){}.getClass().getGenericSuperclass()
    

    But what you are passing into your getFromSource() method is effectively:

    User.class.getGenericSuperclass()
    

    To fix this, you need to update the parameter passed in like this:

    List<User> users = getFromSource("users.json", new ArrayList<User>(){}.getClass());