My goal is to create a Rest Controller that will return an object (let's call it a Car). This Rest Controller is calling an other Rest API (using a header needed to set a token and be authorized to do the call) to get different data from different endpoint in order to mix them. Like if you ask to Tesla about 2 different car models to create a new crazy Car!
The problem is that this other API is giving me an object which looks like {"Name":"automobile2.0","MotorSize":"v12","Color":"Grey","Weight":"2000kg","Year":"2012"}
(actually I receive 28 different fields of different kinds, int, string, array of string, nested json, ... But I only want to keep 3 of them). And I cannot find a way to convert it to my Car object using RestTemplate and Spring Framework.
Also, if I can find a similar way to receive a List<Car>
it will be perfect.
I already tried to use getForObject or getForEntity, unfortunately as I need a header I can't use it.
I was previously doing it by receiving a String and then deserialize it with Genson and a converter, but it didn't not seems to be the best solution.
So now here is my code, first of all, the Car class I want :
public class Car {
@JsonProperty("Name")
private String carName;
@JsonProperty("MotorSize")
private String motorSize;
@JsonProperty("Color")
private String color;
}
And the method I use to do the Rest API call:
public Car getCar() {
UriComponents uriComponents =
UriComponentsBuilder.fromUriString(this.myUrl).build();
HttpHeaders headers = setHeaders(true); //a private method which sets the header
HttpEntity<String> request = new HttpEntity<String>(null, headers); //I don't need a body but I do need a header
ResponseEntity<Car> response = this.restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET, request, new ParameterizedTypeReference<Car>() {});
return response.getBody();
}
I know my call is working because if I do:
ResponseEntity<String> response = this.restTemplate.exchange(uriComponents.toUriString(), HttpMethod.GET, request, String.class);
to replace the response, I get the {"CarName":"automobile2.0","MotorSize":"v12","Color":"Grey"} as response.getBody(), It is what I want but as a String, so wrong format.
What I was expecting to receive from getCar() was a car like:
{
"carName": "automobile2.0",
"motorSize": "v12",
"color": " "grey",
}
Which is next returned by my controller like ResponseEntity<Car>(myCar, HttpStatus.OK)
BUT when I try my controller with Postman, I only receive:
{
"carName": null,
"motorSize": null,
"color": " null,
}
I anyone know how to get my Car from the restTemplate.exchange(...) it will be a great pleasure for me!
Thank you all
Just found the problem... As we was previously using Genson, the JsonProperty annotations was still the one from Genson... So just replace the import for Jackson solved it...