3 回答

TA貢獻1775條經(jīng)驗 獲得超11個贊
您可以使用類似于以下內(nèi)容的靜態(tài)函數(shù):
static <T> List<T> toList(List<Object> object, Class<T> desiredClass) {
List<T> transformedList = new ArrayList<>();
if (object != null) {
for (Object result : object) {
String json = new Gson().toJson(result);
T model = new Gson().fromJson(json, desiredClass);
transformedList.add(model);
}
}
return transformedList;
}
基本上,您只需要確保提供所需的類型(例如desiredClass)并在fromJson.
示例用法:
List<Ticket> ticketList = toList(object, Ticket.class);
List<Price> priceList = toList(object, Price.class);
請注意,通過將 移動object != null到toList-method 中,您無需關(guān)心傳遞給該方法的內(nèi)容。作為回報,您至少會得到一個空列表。

TA貢獻1900條經(jīng)驗 獲得超5個贊
您可以轉(zhuǎn)換代碼段
if (object != null) {
List<Ticket> ticketList = new ArrayList<>();
for (Object result : object) {
String json = new Gson().toJson(result);
Ticket model = new Gson().fromJson(json, Ticket.class);
ticketList.add(model);
}
}
像這樣的泛型
<T> void check(Class<T> type, List<Object> object) {
List<T> ticketList = new ArrayList<>();
for (Object result : object) {
String json = new Gson().toJson(result);
T model = new Gson().fromJson(json, type);
ticketList.add(model);
}
}

TA貢獻1829條經(jīng)驗 獲得超7個贊
<T> List<T> getList(Class<T> type, List<Object> object) {
return object.stream()
.map(result -> new Gson().toJson(result))
.map(new Gson().fromJson(json, type))
.collect(Collectors.toList());
}
List<Ticket> ticketList = getList(Ticket.class, object);
這將完成您的 for 循環(huán)所做的工作。
添加回答
舉報