使用Spring RestTemplate获取JSON对象的列表

Kar*_*udi 186 java spring resttemplate

我有两个问题:

  • 如何使用Spring RestTemplate映射JSON对象列表.
  • 如何映射嵌套的JSON对象.

我正在尝试使用https://bitpay.com/api/rates,遵循http://spring.io/guides/gs/consuming-rest/中的教程.

Mat*_*att 300

首先定义一个对象来保持实体返回数组中.例如

@JsonIgnoreProperties(ignoreUnknown = true)
public class Rate {
    private String name;
    private String code;
    private Double rate;
    // add getters and setters
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用该服务并通过以下方式获取强类型列表:

ResponseEntity<List<Rate>> rateResponse =
        restTemplate.exchange("https://bitpay.com/api/rates",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<Rate>>() {
            });
List<Rate> rates = rateResponse.getBody();
Run Code Online (Sandbox Code Playgroud)

上面的其他解决方案也可以工作,但我喜欢获取强类型列表而不是Object [].

  • 对于Spring 4.2.3而言,这种运行顺利进行 - 正如Matt所说 - 具有避免Object []的巨大优势 (6认同)
  • ParameterizedTypeReference 已@deprecated (2认同)

kam*_*aze 204

也许这样......

ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(urlGETList, Object[].class);
Object[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();
Run Code Online (Sandbox Code Playgroud)

控制器代码 RequestMapping

@RequestMapping(value="/Object/getList/", method=RequestMethod.GET)
public @ResponseBody List<Object> findAllObjects() {

    List<Object> objects = new ArrayList<Object>();
    return objects;
}
Run Code Online (Sandbox Code Playgroud)

ResponseEntity是一个扩展,HttpEntity它添加了一个HttpStatus状态代码.用于RestTemplate以及@Controller方法.在RestTemplate这个类中由getForEntity()和返回exchange().

  • 最好在stackoverflow上查看一些代码片段和示例,或访问offial spring网站...... TblGps [] a = responseEntity.getBody(); (2认同)

小智 71

对我来说这很有效

Object[] forNow = template.getForObject("URL", Object[].class);
    searchList= Arrays.asList(forNow);
Run Code Online (Sandbox Code Playgroud)

Object是您想要的类

  • 即使您使用类而不是像```Coupon [] coupons = restTemplate.getForObject(url,Coupon [] .class)``` (13认同)

小智 10

您可以为每个条目创建 POJO,例如,

class BitPay{
private String code;
private String name;
private double rate;
}
Run Code Online (Sandbox Code Playgroud)

然后使用 BitPay 列表的 ParameterizedTypeReference 您可以用作:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
  "https://bitpay.com/api/rates",
  HttpMethod.GET,
  null,
  new ParameterizedTypeReference<List<BitPay>>(){});
List<Employee> employees = response.getBody();
Run Code Online (Sandbox Code Playgroud)


Too*_*ofy 7

如果你更喜欢一个 POJO 列表,一种方法是这样的:

class SomeObject {
    private int id;
    private String name;
}

Run Code Online (Sandbox Code Playgroud)
public <T> List<T> getApi(final String path, final HttpMethod method) {     
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<List<T>> response = restTemplate.exchange(
      path,
      method,
      null,
      new ParameterizedTypeReference<List<T>>(){});
    List<T> list = response.getBody();
    return list;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

 List<SomeObject> list = someService.getApi("http://localhost:8080/some/api",HttpMethod.GET);
Run Code Online (Sandbox Code Playgroud)

可以在此处找到对上述内容的解释 ( https://www.baeldung.com/spring-rest-template-list ),并在下面进行了释义。

“在上面的代码中发生了一些事情。首先,我们使用 ResponseEntity 作为我们的返回类型,使用它来包装我们真正想要的对象列表。其次,我们调用 RestTemplate.exchange() 而不是 getForObject() .

这是使用 RestTemplate 的最通用方法。它要求我们指定 HTTP 方法、可选的请求正文和响应类型。在这种情况下,我们使用 ParameterizedTypeReference 的匿名子类作为响应类型。

最后一部分允许我们将 JSON 响应转换为适当类型的对象列表。当我们创建 ParameterizedTypeReference 的匿名子类时,它使用反射来捕获有关我们要将响应转换为的类类型的信息。

它使用 Java 的 Type 对象保留这些信息,我们不再需要担心类型擦除。”


bos*_*sco 7

对于那些使用 Spring + Kotlin 的人,翻译如下:

val rates = restTemplate.exchange("https://bitpay.com/api/rates", HttpMethod.GET, null, object : ParameterizedTypeReference<List<Rate>>() {}).body!!
Run Code Online (Sandbox Code Playgroud)

  • kotlin 中的另一种方法是: `val rates =restTemplate.exchange("https://bitpay.com/api/rates", HttpMethod.GET, null, Array&lt;Rate&gt;::class.java).body!! ` (2认同)

Rom*_*n-p 5

经过多次测试,这是我发现的最佳方法:)

Set<User> test = httpService.get(url).toResponseSet(User[].class);
Run Code Online (Sandbox Code Playgroud)

所有你需要的

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}
Run Code Online (Sandbox Code Playgroud)


ana*_*ish 5

这里提到了 3 种替代方法来检索对象列表。所有这些都将完美地工作

@RequestMapping(value = "/emp2", produces = "application/json")
public List<Employee> getEmp2()
{
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<List<Employee>> response = restTemplate.exchange(
            "http://hello-server/rest/employees", HttpMethod.GET,entity, 
    new ParameterizedTypeReference<List<Employee>>() {});
    return response.getBody();
}
Run Code Online (Sandbox Code Playgroud)

(或者)

@RequestMapping(value = "/emp3", produces = "application/json")
public List<Employee> getEmp3()
{
    Employee[] empArray = restTemplate.getForObject("http://hello-server/rest/employees", Employee[].class);
    List<Employee> emp= Arrays.asList(empArray);
    return emp;
}
Run Code Online (Sandbox Code Playgroud)

(或者)

    @RequestMapping(value = "/emp4", produces = "application/json")
public Employee[] getEmp4()
{
    ResponseEntity<Employee[]> responseEntity = restTemplate.getForEntity("http://hello-server/rest/employees", Employee[].class);
    Employee[] empList = responseEntity.getBody();
    //MediaType contentType = responseEntity.getHeaders().getContentType();
    //HttpStatus statusCode = responseEntity.getStatusCode();
    return  empList;
}
Run Code Online (Sandbox Code Playgroud)

雇员.类

public class Employee {

private Integer id;
private String name;
private String Designation;
private String company;

//getter setters and toString()

}
Run Code Online (Sandbox Code Playgroud)