Leonardo
Leonardo

Reputation: 1363

Generic type as parameter for result

I want to create a generic method to return deserialized data. The idea is to pass through parameter a Type.class and when it deserialize using Gson, it returns a collection or a single object from Type.

For example:

public class Client {
    String id;
    String name;

    /* getters and setters */
}

public class Account {
    String number;
    String bank;

   /* getters and setters */
}

public class Main {

    public static void main(String[] args) {
       List<Client> clients = Utils.getList(Client.class, "");
       Account account = Utils.getSingle(Account.class, "number = '23145'");
    }
}

public class Utils {

    public static Class<? extends Collection> getList(Class<?> type, String query) {
        //select and stuff, works fine and returns a Map<String, Object> called map, for example

         Gson gson = new Gson();
         JsonElement element = gson.fromJsonTree(map);

         //Here's the problem. How to return a collection of type or a single type?
         return gson.fromJson(element, type);
    }

    public static Class<?> getSingle(Class<?> type, String query) {
        //select and stuff, works fine and returns a Map<String, Object> called map, for example

         Gson gson = new Gson();
         JsonElement element = gson.fromJsonTree(map);

         //Here's the problem. How to return a collection of type or a single type?
         return gson.fromJson(element, type);
    } 
}

How can I return a single object from Type or a list of it?

Upvotes: 0

Views: 66

Answers (1)

EshtIO
EshtIO

Reputation: 241

First of all you need change method signature to generic type:

public static <T> List<T> getList(Class<T> type, String query)

and

public static <T> T getSingle(Class<T> type, String query)

getSingle method should start working, but for method getList you need to change implementation:

  1. create Type listType = new TypeToken<List<T>>() {}.getType();

  2. return gson.fromJson(element, listType);

you can find more information about com.google.gson.Gson from javaDoc

Upvotes: 2

Related Questions