Resttemplate - request the pojo itself or request

2019-08-26 20:57发布

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?

标签: java json rest
2条回答
Rolldiameter
2楼-- · 2019-08-26 21:17

You can create java object for corresponding json then response will be serialized automatically:

restTemplate.exchange(url, HttpMethod.GET, entity, MyResponseBean.class);

For java bean generation jsonschema2pojo is usefull.

查看更多
孤傲高冷的网名
3楼-- · 2019-08-26 21:28

I think there's at least two reasons to prefer RestTemplate unmarshalling your object for you rather than first retrieving a String:

  1. it's likely more memory-efficient; but much more importantly
  2. it leads to cleaner code!

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 in RestTemplate have an opportunity to read this into your object model byte-by-byte from the response InputStream. 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.

查看更多
登录 后发表回答