Map Nested JSON Objects to Java Classes with Sprin

2020-06-15 03:37发布

I know this may be simple. However, I just can't get it to work.

So I am trying to use Spring RestTemplate to map my JSON data. I have following JSON response from a rest call.

{
  "message":"ok",
  "status":"ok",
  "data":[
      {"Name":"Yo",
       "Address":"100 Test Rd"},
      {...},
      {...}
   ]
}

And here is the class I am trying to map it to.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable {

  private String message;
  private String status;
  private List<Data> data;

  // I could also use a array instead
  // private Data[] data;
}

Here is my Data class:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Data implements Serializable {

  private String Name;
  private String Address;
}

Here is the code I used to call RestTemplate:

public Reponse getResponse() {
    ResponseEntity<Reponse> responseEntity = restTemplate.getForEntity(Url, Reponse.class);

    return responseEntity.getBody();
}

Now here comes the problem. I was able to get "message" and "status", But when I try to log/print data, it shows null. Not exactly sure what's going on here. I really could use some help. Thanks.

7条回答
劫难
2楼-- · 2020-06-15 04:44

I had a similar issue when reading Json data from REST API using Rest Template. To resolve declare getters and setters for the List:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable {

  private String message;
  private String status;
  private List<Data> data;

 // getters and Setters for the list. 


}

The RestTemplate will internally map the values from the listarray to the corresponding array.

查看更多
登录 后发表回答