Reputation: 1363
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
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:
create Type listType = new TypeToken<List<T>>() {}.getType();
return gson.fromJson(element, listType);
you can find more information about com.google.gson.Gson
from javaDoc
Upvotes: 2