我想创建一个返回反序列化数据的泛型方法。我们的想法是传递参数Type.class
,当使用Gson
反序列化时,它会从Type
返回一个集合或一个对象。
例如:
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);
}
}
如何从Type
或其列表中返回单个对象?
答案 0 :(得分:2)
首先,您需要将方法签名更改为泛型类型:
public static <T> List<T> getList(Class<T> type, String query)
和
public static <T> T getSingle(Class<T> type, String query)
getSingle
方法应该开始工作,但对于方法getList
,您需要更改实现:
创建Type listType = new TypeToken<List<T>>() {}.getType();
return gson.fromJson(element, listType);
您可以从javaDoc
找到有关com.google.gson.Gson
的更多信息