gpt4 book ai didi

android - Spring Android RestTemplate 可以返回一个列表吗?

转载 作者:搜寻专家 更新时间:2023-11-01 08:11:00 24 4
gpt4 key购买 nike

我目前在我的android项目中有以下代码:

protected List<Facility> doInBackground(String... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(<SomeWebService>);
httpGet.addHeader("Accept", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Facility>>(){}.getType();
List<Facility> facilities= gson.fromJson(httpClient.execute(httpGet, responseHandler), collectionType);
return facilities;
}catch(Exception e){
e.printStackTrace();
}
return null;
}

在查看 Spring-Android 的 RestTemplate 时,我发现没有办法将 JSON 数组转换为列表(在本例中为 Facility)我用谷歌搜索的所有内容都指向一个对象。我想看看使用 Spring-Android 是否会使上面的代码更简单/更干净,但还没有看到任何让我有任何想法的东西。如何使用 Spring Android 编写上述代码,特别是从模板中获取一个列表?

最佳答案

因为通用信息在运行时不可用,所以您需要这个技巧:创建 List<Facility> 的子类使其可用

public static class FacilityList extends ArrayList<Facility>{
}

...

FacilityListfacilities= gson.fromJson(
httpClient.execute(httpGet, responseHandler),
FacilityList.class);

关于android - Spring Android RestTemplate 可以返回一个列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com