Spring将JSON映射到java POJO

时间:2016-11-25 13:17:27

标签: java spring api pojo

我有API以这种格式返回JSON:

[
    { "shrtName": "abc", "validFrom": "2016-10-23", "name": "aaa", "version": 1 },
    { "shrtName": "def", "validFrom": "2016-11-20", "name": "bbb", "version": 1 },
    { "shrtName": "ghi", "validFrom": "2016-11-22", "name": "ccc", "version": 1 }   
]

我有这个代码,它读取API并将其作为String返回。但我想阅读此API并将其映射到Java POJO类。

public String downloadAPI(){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("API-Key", "4444444-3333-2222-1111-88888888"); 
        HttpEntity<?> requestEntity = new HttpEntity<Object>(headers);
        String URL = "https://aaaaaaa.io/api/v1/aaaaaaaaa?date=2015-04-04;
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
}

我的问题:
1)POJO的格式?
2)我的方法发生了变化(返回类型POJO而不是String)

2 个答案:

答案 0 :(得分:3)

您的JSON是一个数组,这就是[]

的原因

创建POJO

use FOS\RestBundle\Controller\Annotations\Get;

/**
 * @Get("/products/{id}/{month}")
 * @param  string $id Identifier
 * @return [type]     [description]
 *
 * @ApiDoc()
 */
public function getProductsAction($id, $month)
{
    return myfunction($id, $month);
}

删除邮件转换器并将restTemplate交换方法重构为

public class MyPOJO {
    private String shrtName;
    private Date validFrom;
    private String name;
    private int version;    
}

这是我用于GET请求的通用函数

ResponseEntity<MyPOJO[].class> response = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, MyPOJO[].class);

在你的情况下,你可以通过

来调用它
    public <T> T getRequestAndCheckStatus(final String url, final Class<T> returnTypeClass,
                                          final List<MediaType> mediaTypes,
                                          final Map<String, String> headerParams,
                                          final Map<String, Object> queryParams) throws Exception {

        final HttpHeaders headers = new HttpHeaders();
        headers.setAccept(mediaTypes);
        setHeaderParamsIfExists(headers, headerParams);
        final HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
        setQueryParamsIfExists(uriBuilder, queryParams);

        final ResponseEntity<T> entity = restTemplate
                .exchange(getUrl(uriBuilder),
                          HttpMethod.GET,
                          requestEntity,
                          returnTypeClass);

        Assert.assertEquals(HttpStatus.OK, entity.getStatusCode());
        return entity.getBody();
    }

    private void setHeaderParamsIfExists(HttpHeaders headers, Map<String, String> headerParams) {
        if(headerParams != null && !headerParams.isEmpty())
            headerParams.entrySet()
                    .forEach(entry -> headers.set(entry.getKey(), entry.getValue()));
    }

    private void setQueryParamsIfExists(UriComponentsBuilder uriBuilder, Map<String, Object> queryParams) {
        if(queryParams != null && !queryParams.isEmpty())
            queryParams.entrySet()
                    .forEach(entry -> uriBuilder.queryParam(entry.getKey(), entry.getValue()));
    }

    private URI getUrl(UriComponentsBuilder uriBuilder) {
        return uriBuilder.build().encode().toUri();
    }
  • 另外,对于Date,我建议使用long,然后在控制器中将其解析为Date。我看到你使用https协议,你配置了证书吗?

答案 1 :(得分:0)

创建一个包含这些属性的pojo,并使用jackson将json String转换为你的pojo。

public class MapClass {

private String shrtName;
private Date validFrom;
private String name;
private int version;

}