1

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>

srk
  • 4,857
  • 12
  • 65
  • 109

1 Answers1

1

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());
Andy Guibert
  • 41,446
  • 8
  • 38
  • 61
  • Could you add why it is returning HashMap type? – srk May 21 '20 at 18:44
  • Probably because the code was effectively doing `getJsonb().fromJson(is, Object.class)` and the default container object for deserializaing a field with multiple values is to put it into a HashMap – Andy Guibert May 21 '20 at 19:32