Chinthaka Dinadasa
Chinthaka Dinadasa

Reputation: 3461

Mapping dynamic response to Java Object in RestTemplate

I've used RestTemplate to consume remote REST API and I'm getting two different responses for the same request depend on data availability.

eg:- Valid Response

User { username, password }

Error Response when user not found in records.

Error { errorCode, errorMessage }

And this User response has mapped using restTemplate.getForEntity("url", User.class).

Additionally handled RestTemplate Errors using ResponseErrorHandler,

Is there any way to capture both User response and Error Response using resttemplate in same time?

Upvotes: 1

Views: 531

Answers (1)

Ori Marko
Ori Marko

Reputation: 58772

I usually include both/all option and ignore null values, below example

@JsonInclude(Include.NON_NULL)
public class ResponseVO {
    private User user;

    private Error error;
}

If all data in same level, you can add all members in same class

Upvotes: 1

Related Questions