Spring Android RestTemplate能否返回列表?
我目前在android项目中有以下代码:Spring Android RestTemplate能否返回列表?,android,json,spring,Android,Json,Spring,我目前在android项目中有以下代码: protected List<Facility> doInBackground(String... params) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(<SomeWebService>); httpGet.addHeade
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;
}
protectedlist doInBackground(字符串…参数){
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet();
addHeader(“接受”、“应用程序/json”);
ResponseHandler ResponseHandler=新BasicResponseHandler();
试一试{
Gson Gson=新的Gson();
Type collectionType=new-TypeToken(){}.getType();
List facilities=gson.fromJson(httpClient.execute(httpGet,responseHandler),collectionType);
返回设施;
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
在查看SpringAndroid的RestTemplate时,我发现没有办法将JSON数组转换为列表(在本例中为Facility),我在Google上搜索的所有内容都指向一个对象。我想看看使用SpringAndroid是否会使上述代码更简单/更干净,但没有看到任何让我有任何想法的东西。如何使用SpringAndroid编写上述代码,特别是从模板中获取列表 因为通用信息在运行时不可用,所以需要以下技巧:创建
List
的子类以使其可用
public static class FacilityList extends ArrayList<Facility>{
}
...
FacilityListfacilities= gson.fromJson(
httpClient.execute(httpGet, responseHandler),
FacilityList.class);
公共静态类FacilityList扩展了ArrayList{
}
...
FacilityListfacilities=gson.fromJson(
httpClient.execute(httpGet,responseHandler),
设施列表(类别);
因为通用信息在运行时不可用,所以需要以下技巧:创建列表的子类以使其可用
public static class FacilityList extends ArrayList<Facility>{
}
...
FacilityListfacilities= gson.fromJson(
httpClient.execute(httpGet, responseHandler),
FacilityList.class);
公共静态类FacilityList扩展了ArrayList{
}
...
FacilityListfacilities=gson.fromJson(
httpClient.execute(httpGet,responseHandler),
设施列表(类别);
另一种解决方案是将列表检索为数组,然后将其转换为:
Type collectionType = new TypeToken<Facility[]>(){}.getType();
Facility[] facilities= gson.fromJson(httpClient.execute(httpGet, responseHandler), collectionType);
return Arrays.asList(facilities);
Type collectionType=new-TypeToken(){}.getType();
Facility[]facilities=gson.fromJson(httpClient.execute(httpGet,responseHandler),collectionType);
返回数组。asList(设施);
另一种解决方案是将列表检索为数组,然后将其转换为:
Type collectionType = new TypeToken<Facility[]>(){}.getType();
Facility[] facilities= gson.fromJson(httpClient.execute(httpGet, responseHandler), collectionType);
return Arrays.asList(facilities);
Type collectionType=new-TypeToken(){}.getType();
Facility[]facilities=gson.fromJson(httpClient.execute(httpGet,responseHandler),collectionType);
返回数组。asList(设施);