We already know how to convert from JSON to an object or a list of objects (deserialization) in Java with Gson - see JSON to Object and Object to JSON in Java with GSON and JSON to Array or JSON to List with GSON in Java

What if we don’t know in advance what Java type it is?

To do this we obviously need to use generics.

This is how

JSON to generic object

    public <T> T fromJson(String json, Class<T> clazz) {
        return new Gson().fromJson(json, clazz);
    }

JSON to list of generic objects

    public <T> List<T> fromJsonAsList(String json, Class<T[]> clazz) {
        return Arrays.asList(new Gson().fromJson(json, clazz));
    }

Generic Deserialization usage

    Book book = fromJson(jsonBookString, Book.class);

    List<Book> books = fromJsonAsList(jsonBooksString, Book[].class)

See how that approach is used in Easy Files - the open source library that lets you read files with easy.

Give Easy Files a star on GitHub if you like it.


You may also find these posts interesting: