我有两个问题:

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

我试图消费https://bitpay.com/api/rates,从http://spring.io/guides/gs/consuming-rest/遵循教程。


当前回答

在我的情况下,我更喜欢提取一个字符串,然后使用JsonNode接口浏览上下文

    var response =  restTemplate.exchange("https://my-url", HttpMethod.GET, entity,  String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        var jsonString = response.getBody();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonString);           
        
        System.out.println(actualObj);  
    }

或者很快

ObjectNode actualObj= restTemplate.getForObject("https://my-url", ObjectNode.class);

然后读取内部数据与路径表达式,即。

boolean b = actualObj.at("/0/states/0/no_data").asBoolean();

其他回答

对我来说这很有效

Object[] forNow = template.getForObject("URL", Object[].class);
    searchList= Arrays.asList(forNow);

Object是你想要的类的位置

也许这样……

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

RequestMapping的控制器代码

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

    List<Object> objects = new ArrayList<Object>();
    return objects;
}

ResponseEntity是HttpEntity的扩展,它添加了HttpStatus状态码。在RestTemplate和@Controller方法中使用。 在RestTemplate中,该类由getForEntity()和exchange()返回。

对于那些使用Spring + Kotlin的人来说,下面是翻译:

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

实际上,我之前为我的一个项目开发了一些功能,以下是代码:

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the return type you are expecting. Exemple : someClass.class
 */

public static <T> T getObject(String url, Object parameterObject, Class<T> returnType) {
    try {
        ResponseEntity<T> res;
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        String json = mapper.writeValueAsString(restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, returnType).getBody());
        return new Gson().fromJson(json, returnType);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the type of the returned object. Must be an array. Exemple : someClass[].class
 */
public static <T> List<T> getListOfObjects(String url, Object parameterObject, Class<T[]> returnType) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        ResponseEntity<Object[]> results = restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, Object[].class);
        String json = mapper.writeValueAsString(results.getBody());
        T[] arr = new Gson().fromJson(json, returnType);
        return Arrays.asList(arr);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

我希望这能帮助到别人!

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

Set<User> test = httpService.get(url).toResponseSet(User[].class);

这就是你所需要的

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());
}