I got two options:
Requesting the object
restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
or requesting the JSON
restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
and parse it afterwards.
Behind the scenes both will be using JSON, but is there any convention or best practice?
You can create java object for corresponding json then response will be serialized automatically:
For java bean generation jsonschema2pojo is usefull.
I think there's at least two reasons to prefer
RestTemplate
unmarshalling your object for you rather than first retrieving aString
:If you retrieve a
String
directly, you have to first read that whole result into memory, and then parse this into your object model. The message converters inRestTemplate
have an opportunity to read this into your object model byte-by-byte from the responseInputStream
. Granted, they may not be able to build an object graph without loading the whole response into memory anyway, but at least this way you don't have to do it twice.But more importantly... why would you do this yourself, when Spring has battle-hardened, infinitely configurable code to do this for you?
Say that, every time you get a JSON response from RestTemplate, you deal with it yourself with:
MyThing thing = objectMapper.readValue(stringResult, MyThing.class);
...isn't even that one line worth saving? Coupled with this, I'd argue that JSON umarshalling is inherently a cross-cutting concern that makes sense to be configured centrally.