0

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?

3
  • And... what's the question? Commented Nov 29, 2017 at 18:07
  • 1
    A hint: When asking for help, make it easy for people to understand what you are asking. Burying the question in code comments does not make it easy. Commented Nov 29, 2017 at 18:10
  • Don't use raw types.
    – shmosel
    Commented Nov 29, 2017 at 22:07

1 Answer 1

2

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

1
  • 1
    thanks for your answer. Shouldn't I set new TypeToken<List<type> somehow?
    – Leonardo
    Commented Nov 30, 2017 at 12:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.