首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Android RestTemplate可以返回列表吗?

Spring Android RestTemplate可以返回列表吗?
EN

Stack Overflow用户
提问于 2012-03-10 01:55:33
回答 2查看 1.9K关注 0票数 2

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

代码语言:javascript
复制
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编写上述代码,特别是从模板中获取一个列表?

EN

回答 2

Stack Overflow用户

发布于 2012-03-10 03:34:45

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

代码语言:javascript
复制
public static class FacilityList extends ArrayList<Facility>{
}

...

FacilityListfacilities= gson.fromJson(
    httpClient.execute(httpGet, responseHandler),
    FacilityList.class);
票数 4
EN

Stack Overflow用户

发布于 2012-09-28 17:31:17

另一种解决方案是以数组的形式检索列表,然后将其转换:

代码语言:javascript
复制
Type collectionType = new TypeToken<Facility[]>(){}.getType();
Facility[] facilities= gson.fromJson(httpClient.execute(httpGet, responseHandler), collectionType);
return Arrays.asList(facilities);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9638728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档