Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: RestTemplate returns null object

With the below GET request:

ResponseEntity<String> entity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class );
entity.getBody();

returns a JSON String like this:

{"userRegistrations":[{"userRegistrationToken":"fb398972","userRegistrationTokenAlias":"87f15f8"}]}

But I want to make this work with an object not with a string. So with the code below I receive a UserRegistrations object with a null UserTokenResponse List

ResponseEntity<UserRegistrations> entity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, UserRegistrations.class );
entity.getBody();

And my domain class looks like this:

public class UserRegistrations {
    List<UserTokenResponse> userRegistrationList;
    //..getters and setters
}

public class UserTokenResponse {
   private String userRegistrationToken;
   private String userRegistrationTokenAlias;
   //getters and setters
}

What am I missing?

like image 466
Spring Avatar asked Dec 14 '16 18:12

Spring


1 Answers

Assuming you're using Jackson, RestTemplate automatically registers a MappingJackson2HttpMessageConverter which configures the underlying ObjectMapper to ignore unknown properties.

The JSON object has a single attribute named userRegistrations, whereas your Java class has a single attribute named userRegistrationList. They don't match.

They need to match, or you need to add a @JsonProperty annotation of the attribute to make Jackson serialize/parse it as userRegistrations.

like image 104
JB Nizet Avatar answered Sep 18 '22 11:09

JB Nizet