Spring Boot RestTemplate列表 [英] Spring Boot RestTemplate List

查看:148
本文介绍了Spring Boot RestTemplate列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这样的回复:

{  
   "data":[  
      {  
         "object1":"example",
         "object2":"example",
         "object3":"example",
         "object4":"example",
         "object5":"example"
      },
      {  
         "object1":"example",
         "object2":"example",
         "object3":"example"
      }
   ]
}

现在我我希望将这些数据映射到我的类DTO,但是我得到一个错误,因为DTO没有数据字段。我希望它在 List 或我的类的数组中。
赞:

Now I wanted to Map this data to my class DTO but there I get an "error" because the DTO has no data field. I want it in a List or Array of my class. Like:

List<MyClass> list = restTemplate.getForObject(url, MyClass.class);

我希望你知道我的意思吗?

I hope you know what I mean?

推荐答案

我想到的一种方法是将JSON响应转换为 Map< String,List< MyClass>> 然后查询地图,即 map.get(data),以获得实际的列表< MyClass>

One approach comes to mind is to convert the JSON response to a Map<String, List<MyClass>> and then query the map, i.e. map.get("data"), to get the actual List<MyClass>.

为了将JSON响应转换为 Map< String,List< MyClass>> ,您需要定义类型引用

In order to convert the JSON response to Map<String, List<MyClass>>, you need to define a Type Reference:

ParameterizedTypeReference<Map<String, List<MyClass>>> typeRef = 
                           new ParameterizedTypeReference<Map<String, List<MyClass>>>() {};

然后将 typeRef 传递给 exchange 方法如下:

Then pass that typeRef to the exchange method like the following:

ResponseEntity<Map<String, List<MyClass>>> response = 
                                 restTemplate.exchange(url, HttpMethod.GET, null, typeRef);

最后:

System.out.println(response.getBody().get("data"));

如果您想知道为什么我们需要类型参考,请考虑阅读Neal Gafter关于的帖子超级型代币

If you're wondering why we need a type reference, consider reading Neal Gafter's post on Super Type Tokens.

更新:如果您要反序列化以下架构:

Update: If you're going to deserialize the following schema:

{
    "data": [],
    "paging": {}
}

最好创建一个如下所示的哑容器类:

It's better to create a dumb container class like the following:

class JsonHolder {
    private List<MyClass> data;
    private Object paging; // You can use custom type too.

    // Getters and setters
}

然后使用它在 RestTemplate 调用中:

JsonHolder response = restTemplate.getForObject(url, JsonHolder.class);
System.out.println(response.getData()); // prints a List<MyClass>
System.out.println(response.getPaging()); // prints an Object

这篇关于Spring Boot RestTemplate列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆