目前,我的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编写上述代码,特别是从模板中获取一个列表?
发布于 2012-03-10 03:34:45
因为泛型信息在运行时不可用,所以您需要这个技巧:创建List<Facility>的子类以使其可用
public static class FacilityList extends ArrayList<Facility>{
}
...
FacilityListfacilities= gson.fromJson(
httpClient.execute(httpGet, responseHandler),
FacilityList.class);发布于 2012-09-28 17:31:17
另一种解决方案是以数组的形式检索列表,然后将其转换:
Type collectionType = new TypeToken<Facility[]>(){}.getType();
Facility[] facilities= gson.fromJson(httpClient.execute(httpGet, responseHandler), collectionType);
return Arrays.asList(facilities);https://stackoverflow.com/questions/9638728
复制相似问题