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.
I ran into the same issue. Annotate with
@JsonProperty
:The fields of your
Data
class should now get populated, and you can name your fields independent of the JSON representation (e.g.name
instead ofName
).I know this is an old thread.
But for anyone having the same problem, you can use
MappingJackson2HttpMessageConverter
for this purpose with Jackson.Please refer the answer given in this thread.
Please use
private List<Data> data = new AllarList<Data>( )
; and please provide getters( ) and setters( ) methods in both the classes.Put
@JsonInclude(Include.NON_EMPTY)
above Data classPlease add below dependencies under section at your main POM.xml file and do maven compile. Then I guess your issue will get resolved.
If you need only print data, you can do this
I was having a similar issue with RestTemplate not mapping nested JSON objects to my class model also, after much frustration I decided to retrieve my JSON as a String(instead of converting directly to my target object) using RestTemplate and then use the google Gson library to convert my String to my target entity.
pom.xml
code to call RestTemplate:
Unfortunately I was unable to find out why my nested objects were not mapped using RestTemplate the first place but I hope this workaround helps!
Annotate property "data" with @JsonUnwrapped as below