在RestTemplate中映射复杂的JSON对象

时间:2017-02-04 08:40:19

标签: java json resttemplate spring-boot-gradle-plugin

JSON的结构如下:

{
 "id": "0001",
 "type": "portable",
 "name": "mobile",
 "results":[
   { 
    "company": "Apple",
    "country": "US", 
    "city": "Cupertino"
   },
   { 
    "company": "Google",
    "country": "Japan", 
    "city": "Tokyo"
   }
  ]
}

我尝试将上面的json映射到我的“Response”类,但我只能检索id,类型和名称。对于json对象,“结果”显示结果:[]。 这是我实施的代码;

CompanyDetail类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class CompanyDetail {
    public String company;
    public String country;
    public String city;

   //getters and setters
}

公司类:

    @JsonIgnoreProperties(ignoreUnknown = true)
public class CompanyD {
    public String name;
    public List<Detail> result;

   //getters and setters
}

实施班:

  @Override
  public ResponseEntity<String> getResponseEntity() {       
      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate .getForEntity(
      "url", String.class);       
      logger.info("Response:"+response);
      return response;
}

    @Override
    public Company getResponseObject() {
        RestTemplate restTemplate=new RestTemplate();
        Company comp=(Company) restTemplate.getForObject("url",
                     Company.class,200);
        List<CompanyDetail> companyInfo = comp.getCompanyDetail();
        for (CompanyDetail companyDetail : companyInfo) {
            logger.info("Country:"+companyDetail.getCountry());
            logger.info("City:"+companyDetail.getCity());
            logger.info("Company:"+companyDetail.getCompany());
        }
    return comp;

从两个实现方法中我得到“results”json对象的空值。我无法弄清楚我的代码有什么问题。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题但是在你的情况下看起来像拼写错误了#34; resluts&#34;。