这是将 retrofit 响应作为对象获取的代码。下面的方法工作正常,但我需要一个通用函数来执行上述功能,即类名可能会有所不同。 (例如)门票、价格、代币、预约,如下所示:
processGETRequest(AppController.getApiHelper().searchTickets(from, to), new RetrofitListener() {
@Override
public void onSuccess(Object object) { }
@Override
public void onSuccess(List<Object> object) {
// Here I'm getting retrofit response as a object //
if (object != null) {
// Below method is working fine //
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);
}
// I need an one common function for performing above functionality
// i.e the Class name may vary.. (e.g) Ticket, Price, Token, Appointment like this.
}
}
@Override
public void onError(String error) {
Log.d("error: ", " " + error);
}
}, false);
RetrofitListener
接口(interface)很简单:
public interface RetrofitListener {
void onSuccess(Object object);
void onSuccess(List<Object> object);
void onError(String error);
}
最佳答案
您可以使用类似于以下的静态函数:
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
方法中,您无需关心传递给该方法的内容。作为返回,您至少会得到一个空列表。
关于java - 如何将 List<Object> 转换为 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52071416/