You don't even need ResponseEntitys! Just use getForObject with a String.class like:

final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);

System.out.println(response);

It will print something like:

{
  "origin": "1.2.3.4"
}
Answer from madhead on Stack Overflow
Discussions

java - Get list of JSON objects with Spring RestTemplate - Stack Overflow
I have two questions: How to map a list of JSON objects using Spring RestTemplate. How to map nested JSON objects. I am trying to consume https://bitpay.com/api/rates, by following the tutorial fro... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Receiving a JSON string response from a URL - Code Review Stack Exchange
I am using RestTemplate as my HttpClient to execute a URL while the server will return a JSON string as the response. The customer will call this library by passing DataKey object which has userId in it. Earlier I was using AsyncRestTemplate which is part of Spring 4 but in my company they are not supporting Spring 4 in their parent pom so going back to Spring 3 for now. Using the given userId, I will find out what are the machines that I can hit to get ... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
February 15, 2018
java - GET request in RestTemplate in JSON - Stack Overflow
It's been troubling for a couple days already for a seemingly super straightforward question: I'm making a simple GET request using RestTemplate in application/json, but I keep getting org. More on stackoverflow.com
๐ŸŒ stackoverflow.com
spring - RestTemplate and acessing json - Stack Overflow
I have seen the responses from many other posts but would like to understand if there is a better way to do the same thing. Requirement:- I am using restTemplate to talk to web service which returns More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ in spring resttemplate, how can i retrieve a specific single field from the obtained json response
r/learnjava on Reddit: In Spring RestTemplate, how can I retrieve a specific single field from the obtained JSON response
June 21, 2024 -

I am using an api to retrieve some data which I did get but from that list of data I only want some stuffs I tried all the method yet nothing seems to work

this is the example JSON object

I am trying to only retrieve title and original tile

expect response is 200 but result is empty screen (in postman)

Thanks :)

---------------------------result from API in postman----------------------------------------

{

    "page": 1,
    "results": [
        {
            "backdrop_path": "/nxxCPRGTzxUH8SFMrIsvMmdxHti.jpg",
            "id": 639720,
            "original_title": "IF",
            "overview": "A young girl who goes through a difficult experience begins to see everyone's imaginary friends who have been left behind as their real-life friends have grown up.",
            "poster_path": "/xbKFv4KF3sVYuWKllLlwWDmuZP7.jpg",
            "media_type": "movie",
            "adult": false,
            "title": "IF",
            "original_language": "en",
            "genre_ids": [
                35,
                14,
                10751
            ],
            "popularity": 937.037,
            "release_date": "2024-05-08",
            "video": false,
            "vote_average": 7.477,
            "vote_count": 244
        },
    
  
----------------------------------------MY spring boot code below----------------------------

u/Slf4j
u/Service
public class MovieServices {

    u/Setter
    u/Getter
    u/JsonIgnoreProperties(ignoreUnknown = true)
  static  class CollectionofMovies{

        public List<MyMovies> result;
    }

    u/Getter
    u/Setter
    u/JsonIgnoreProperties(ignoreUnknown = true)
 static  class MyMovies{

        u/JsonProperty("original_title")
        public String originalTitle;

        u/JsonProperty("title")
        public String title;
    }


private static final String url="https://api.themoviedb.org/3/trending/all/day?language=en-US";
private static final String key="Bearer --ooo"
    u/Autowired
    private RestTemplate restTemplate;
    public List<MyMovies> allmovies() {

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("accept", "application/json");
            headers.set("Authorization",key);
            ResponseEntity<CollectionofMovies> response=restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), new ParameterizedTypeReference<CollectionofMovies>() {
            });
            if(response.getBody()!=null){
                return response.getBody().getResult();
            }
            else {
                throw new IllegalStateException("Response body is null");
            }
        }
        catch (Exception e){
            log.error("Something went wrong");
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,"Error while fetching api ",e);
        }

    }
}
Top answer
1 of 4
2
RestTemplate uses an ObjectMapper to read objects from a JSON string. I worked through your issue by creating a test. Instead of worrying about the RestTemplate and calling an API, the test just reads a MoviePage from JSON using an ObjectMapper. public class MoviePageTests { @Value @Builder @Jacksonized @JsonIgnoreProperties(ignoreUnknown = true) static class MoviePage { @NonNull List results; } @Value @Builder @Jacksonized @JsonIgnoreProperties(ignoreUnknown = true) @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) static class MoviePageResult { @NonNull String title; @NonNull String originalTitle; } @Test public void canReadFromJson() { var json = """ { "page": 1, "results": [ { "backdrop_path": "/nxxCPRGTzxUH8SFMrIsvMmdxHti.jpg", "id": 639720, "original_title": "IF", "overview": "A young girl who goes through a difficult experience begins to see everyone's imaginary friends who have been left behind as their real-life friends have grown up.", "poster_path": "/xbKFv4KF3sVYuWKllLlwWDmuZP7.jpg", "media_type": "movie", "adult": false, "title": "IF", "original_language": "en", "genre_ids": [ 35, 14, 10751 ], "popularity": 937.037, "release_date": "2024-05-08", "video": false, "vote_average": 7.477, "vote_count": 244 } ] } """; var objectMapper = new ObjectMapper(); try { var actual = objectMapper.readValue(json, MoviePage.class); var expected = MoviePage .builder() .results( List.of( MoviePageResult .builder() .title("IF") .originalTitle("IF") .build() ) ) .build(); assertThat(actual).isEqualTo(expected); } catch (JsonProcessingException e) { throw new AssertionError(e); } } } Reducing the scope of the problem can help tackle issues like this.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2017 โ€บ 02 โ€บ how-to-consume-json-from-restful-web-services-Spring-RESTTemplate-Example.html
How to Consume JSON from RESTful Web Service and Convert to Java Object - Spring RestTemplate Example
All you need to tell is the name of the class you want to map the incoming JSON response. We have first created an instance of RestTemplate class and then called the getForObject() method. This accepts two parameters.
Top answer
1 of 1
9
  1. I would consider creating an AsyncClient and a SyncClient interface/classes instead of one. I guess users of the current Client class would use only one of the two methods. Furthermore, getSyncData does not use any of the fields of DataClient currently.

    Async version:

    public class AsyncDataClient {
    
        private RestTemplate restTemplate = new RestTemplate();
        private ExecutorService service = Executors.newFixedThreadPool(15);
    
        public Future<DataResponse> getAsyncData(DataKey key) {
            DataFetcherTask task = new DataFetcherTask(key, restTemplate);
            Future<DataResponse> future = service.submit(task);
    
            return future;
        }
    }
    

    Sync version:

    public class SyncDataClient {
    
        private AsyncDataClient asyncDataClient;
    
        public SyncDataClient(final AsyncDataClient asyncDataClient) {
            this.asyncDataClient = checkNotNull(asyncDataClient, "asyncDataClient cannot be null");
        }
    
        public DataResponse getSyncData(DataKey key) {
            ...
            responseFuture = asyncDataClient.getAsyncData(key);
            ...
        }
    }
    

    See also: Interface segregation principle

  2. In getSyncData the response variable is used for multiple purposes. It could store a valid response and error responses too. I would use separate variables for these purposes for better readability and smaller variable scope:

    public DataResponse getSyncData(DataKey key) {
        Future<DataResponse> responseFuture = null;
    
        try {
            responseFuture = asyncDataClient.getAsyncData(key);
            final DataResponse response = responseFuture.get(key.getTimeout(), key.getUnitOfTime());
            return response;
        } catch (TimeoutException ex) {
            final DataResponse response = new DataResponse(DataErrorEnum.CLIENT_TIMEOUT, DataStatusEnum.ERROR);
            responseFuture.cancel(true); // terminating the tasks that have got
                                         // timed out
            return response;
        } catch (Exception ex) {
            return new DataResponse(DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);
        }
    }
    

    It also makes easier to figure out that the only occasion when this method returns null is the try block, when the future returns null.

    See also: Effective Java, Second Edition, Item 45: Minimize the scope of local variables

  3. In this catch block you loose the cause of the error:

    } catch (Exception ex) {
        response = new DataResponse(DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);
    }
    

    An operator would be helpful for (at least) a debug level log message here. It could save you lots of debugging time.

  4. DataKey contains at least these methods:

    • getTimeout()
    • getUnitOfTime()
    • getTypeOfFlow()
    • getUserId()
    • getEntity()

    It reminds me a DataRequest object name instead. Consider renaming. For me, DataKey is closer to a cache key class or something like that. Furthermore, getEntity is still smells even in a request class. It might be a third parameter of getAsyncData and the constructor of DataFetcherTask as well.

  5. The of hostnames reference could be a simple List<String> instead of

    LinkedList<String> hostnames = ...
    

    As far as I see the code does not use any LinkedList specific methods.

    See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfaces

  6. This:

    if (CollectionUtils.isEmpty(hostnames)) {
    

    Could be changed to

     if (hostnames.isEmpty()) {
    

    CollectionUtils checks nulls as well, but if it's a null you get a NullPointerException in the for loop earlier.

  7. Instead of StringUtils.isEmpty(hostname) I usually prefer StringUtils.isBlank which handles whitespace-only strings too.

  8. I don't know how complex is your generateURL method but I would consider moving it to an UrlGenerator method. I would also call it generateUrl for a little bit better readability.

    From Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions:

    While uppercase may be more common, a strong argument can made in favor of capitalizing only the first letter: even if multiple acronyms occur back-to-back, you can still tell where one word starts and the next word ends. Which class name would you rather see, HTTPURL or HttpUrl?

  9. You could move this part at the beginning of your method as a guard clause:

    // if hostnames are empty, then sending different ERROR ENUM code.
    if (hostnames.isEmpty()) {
        dataResponse = new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);
    

    For example:

    List<String> hostnames = mappings.getListOfHostnames(key.getUserId());
    // if hostnames are empty, then sending different ERROR ENUM code.
    if (hostnames.isEmpty()) {
        return new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);
    }
    
  10. Instead of the break statement in the loop you could return immediately:

    if (response.getStatusCode() == HttpStatus.NO_CONTENT) {
        return new DataResponse(response.getBody(), DataErrorEnum.NO_CONTENT, DataStatusEnum.SUCCESS);
    } else {
        return new DataResponse(response.getBody(), DataErrorEnum.OK, DataStatusEnum.SUCCESS);
    }
    

    It also helps to make the scope of dataResponse variable smaller. Actually, you don't need it at all and you could get rid of the null comparison at the end of the method too:

    @Override
    public DataResponse call() {
        ...
        List<String> hostnames = mappings.getListOfHostnames(key.getUserId());
        if (hostnames.isEmpty()) {
            return new DataResponse(null, DataErrorEnum.PERT_ERROR, DataStatusEnum.ERROR);
        }
    
        for (String hostname: hostnames) {
            ...
            try {
                ...
                ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, key.getEntity(), String.class);
                ...
                if (response.getStatusCode() == HttpStatus.NO_CONTENT) {
                    return new DataResponse(response.getBody(), DataErrorEnum.NO_CONTENT, DataStatusEnum.SUCCESS);
                } else {
                    return new DataResponse(response.getBody(), DataErrorEnum.OK, DataStatusEnum.SUCCESS);
                }
            } catch (HttpClientErrorException ex) {
                ...
                return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);
            } catch (HttpServerErrorException ex) {
                ...
                return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);
            } catch (RestClientException ex) {
                // if it comes here, then it means some of the servers are down so adding it into block list
                ShardMapping.blockHost(hostname);
            }
        }
    
        // either  all the servers are down or all the servers were in block list
        return new DataResponse(null, DataErrorEnum.SERVICE_UNAVAILABLE, DataStatusEnum.ERROR);
    }
    

    Also note the scope change of response.

  11. I don't see why you need this casting:

    } catch (HttpClientErrorException ex) {
        HttpStatusCodeException httpException = (HttpStatusCodeException) ex;
    

    and this one:

    } catch (HttpServerErrorException ex) {
        HttpStatusCodeException httpException = (HttpStatusCodeException) ex;
    

    Since HttpStatusCodeException is a superclass of both HttpClientErrorException and HttpServerErrorException the following is the same:

        } catch (HttpClientErrorException ex) {
            HttpStatusCodeException httpException = ex;
            ...
        } catch (HttpServerErrorException ex) {
            HttpStatusCodeException httpException = ex;
    

    Furthermore, HttpStatusCodeException has only these two subclasses in Spring and the body of both catch clauses are the same so you could simply catch only HttpStatusCodeException here:

    } catch (HttpStatusCodeException httpException) {
        DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);
        String errorMessage = httpException.getResponseBodyAsString();
        return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);
    } catch (RestClientException ex) {
        // if it comes here, then it means some of the servers are down so adding it into block list
        ShardMapping.blockHost(hostname);
    }
    

    Keep in my that anyone can create a new subclass of HttpStatusCodeException so that's might not what you want.

    If you're using Java 7 or later, you could use multi-catch with one catch block:

    } catch (HttpClientErrorException | HttpServerErrorException ex) {
    

    Another solution is extracting out the common code into a method:

     private DataResponse createErrorResponse(HttpStatusCodeException httpException) {
        DataErrorEnum error = DataErrorEnum.getErrorEnumByException(httpException);
        String errorMessage = httpException.getResponseBodyAsString();
        return new DataResponse(errorMessage, error, DataStatusEnum.ERROR);
    }
    

    Usage:

    } catch (HttpClientErrorException ex) {
        return createErrorResponse(ex);
    } catch (HttpServerErrorException ex) {
        return createErrorResponse(ex);
    
  12. responseFuture.cancel(true) is in a catch block. I have not checked but I would try to move it into a finally block. If another (non-timeout exception) happens you won't use the future anyway.

  13. getUnitOfTime does not suggest any connection with the getTimeout method. I would rename it to getTimeoutUnit.

๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ spring โ€บ spring boot โ€บ get list of json objects with spring resttemplate
Get list of JSON objects with Spring RestTemplate | Baeldung
December 11, 2025 - When the response to a REST request is a JSON array, there are a few ways we can convert it to a Java collection. Letโ€™s look at the options and see how easily they allow us to process the data that is returned. Weโ€™ll look at extracting the usernames of some user objects returned by a REST service. First, letโ€™s make the call with RestTemplate.getForEntity and use a ResponseEntity of type Object[] to collect the response:
๐ŸŒ
Springcloud
springcloud.io โ€บ post โ€บ 2022-03 โ€บ spring-resttemplate
Complete Guide to Spring RestTemplate - Spring Cloud
March 31, 2022 - Here we are using the getForEntity() method of the RestTemplate class to invoke the API and get the response as a JSON string.
Find elsewhere
Top answer
1 of 2
1

OK, eventually, one of my co-workers helped me figure out why, believe it or not, it's this simple:

The endpoint was like this: "http:localhost:8080/api/v1/items?itemIds=" + URLEncoder.encode(itemIds, "UTF-8");

However, it should be "http:localhost:8080/api/v1/items?itemIds=" + itemIds;

itemIds is just a comma-separated list.

After URLEncoder encoding via "UTF-8" schema, this comma-separated list becomes itemIds=5400028914%2C5400029138%2C5400029138%2C5400029138%2C5400029138%2C5400028401%2C5400028918%2C5400028076

from

itemIds=5400028914,5400029138,5400029138,5400029138,5400029138,5400028401,5400028918,5400028076,5400028726

We don't need to URLEncoder to encode the URL when using RestTemplate, anyone could help me deepen my understanding here please?

Thanks!

2 of 2
0

You don't need set "requestEntity" for a GET method, try your code like this:

public ItemInfo getItemInfo() throws Exception {
    String url =
            "http://localhost:8080/api/v1/items?itemIds=abc";
    ObjectMapper objectMapper = new ObjectMapper();     
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
    String responseBody = response.getBody();
    handlerError(response, url);
    try {
        return objectMapper.readValue(responseBody, ItemInfo.class);
    } catch (IOException exception) {
        LOGGER.error("failed to send REST request", exception);
        throw new Exception(ErrorCode.NOT_AVAILABLE, url);
    }
}

private void handlerError(final ResponseEntity<String> response, final String url) throws Exception {
    String responseBody = response.getBody();
    try {
        if (RestUtil.isError(response.getStatusCode())) {
            ObjectMapper objectMapper = new ObjectMapper(); 
            MyInfoError myInfoError = objectMapper.readValue(responseBody, MyInfoError.class);
            throw new Exception(infoErreur, ErrorCode.UNKNOWN_CODE_ERROR);
        } else if (RestUtil.isNotFound(response.getStatusCode())) {
            throw new Exception(ErrorCode.NOT_AVAILABLE, "MyService");
        }
    } catch (IOException exception) {
        LOGGER.error("failed to send REST request", exception);
        throw new Exception(ErrorCode.NOT_AVAILABLE, url);
    }
}

I put it NULL because GET method not send any JSON request body/headers:

restTemplate.exchange(url, HttpMethod.GET, null, String.class);

OR: put your headers in GET method like this:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<?> requestEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

For Example for POST you need to set requestEntity like below:

ItemFormRequest request =
            new ItemFormRequest(1,"item no", "item name");
HttpEntity<ItemFormRequest> requestEntity = new HttpEntity<>(request);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String responseBody = response.getBody();

Hope this help :)

๐ŸŒ
W3Docs
w3docs.com โ€บ java
Get list of JSON objects with Spring RestTemplate
Here's an example of how you can get a list of JSON objects using the RestTemplate: String url = "http://example.com/api/objects"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<List<Object>> response = restTemplate.exchange( ...
๐ŸŒ
Spring
docs.spring.io โ€บ spring-android โ€บ docs โ€บ current โ€บ reference โ€บ html โ€บ rest-template.html
2. RestTemplate Module
// Add the identity Accept-Encoding header HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAcceptEncoding(ContentCodingType.IDENTITY); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(); // Add the String message converter restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); // Make the HTTP GET request, marshaling the response to a String ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); Suppose you have defined a Java object you wish to populate from a RESTful web request that returns JSON content.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49022249 โ€บ resttemplate-request-response-simple-json-string
java - RestTemplate Request/Response simple JSON-String - Stack Overflow
HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("name", "charlie") .queryParam("type", "clown") .queryParam("age", "35") .queryParam("country", "JPA"); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> response = restTemplate.exchange( builder.build().encode().toUri(), HttpMethod.GET, entity, String.class);
Top answer
1 of 3
5
  1. As of the "main key is result":

    a. I would create a wrapper class for the actual payload if you deal with just one of this kind of web service:

    public class Return{
        // Class property cannot be called "return" because it is Java reserved name.
        @JsonProperty("return")
        private User[] array;
        .... getter and setter
    }
    

    b. If you deal with multiple webservices where actual payload is in "return" field I would create a generic wrapper class :

    public class Return<T>{
        // Class property cannot be called "return" because it is Java reserved name.
        @JsonProperty("return")
        private T[] array;
        .... getter and setter
    }
    

    Call to RestRemplate:

    ResponseEntity<Return<User>> response = restTemplate.exchange(URL_GET, 
            HttpMethod.GET, request, new ParameterizedTypeReference<Return<User>>(){});
    User[] usersArray = response2.getBody().getArray();
    
  2. As of the property value in JSON attribute called "value" I would create two custom JsonDeserializer(s): one for single value and one for array of values and annotate each property with @JsonDeserialize where it applies:

    Single value deserializer:

    public class StringValueDeserializer  extends JsonDeserializer<String>{
    
        @Override
        public String deserialize(JsonParser parser, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            ObjectCodec codec = parser.getCodec();
            TreeNode node = codec.readTree(parser);
            JsonNode value = (JsonNode)node.get("value");
    
            if (value != null){
                return value.asText();
            }
            return null;
        }
    }
    

    Array of values derializer:

    public class StringArrayValueDeserializer  extends JsonDeserializer<List<String>>{
    
        @Override
        public List<String> deserialize(JsonParser parser, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
    
            List<String> ret = new ArrayList<>();
    
            ObjectCodec codec = parser.getCodec();
            TreeNode node = codec.readTree(parser);
    
            if (node.isArray()){
                for (JsonNode n : (ArrayNode)node){
                    JsonNode value = n.get("value");
                    if (value != null){
                        ret.add(value.asText());
                    }
                }
            }
            return ret;
        }
    }
    

    Here you are new User.class:

    public class User {
    
        private boolean admin;
    
        private String alias;
    
        private String email;
    
        @JsonDeserialize(using = StringValueDeserializer.class)
        private String emailId;
    
        @JsonDeserialize(using = StringArrayValueDeserializer.class)
        private ArrayList<String> groups;
    
        @JsonDeserialize(using = StringValueDeserializer.class)
        private String id;
    
        private boolean locked;
    
        private int loggedInCount;
    
        private boolean master;
    
        private String sms;
    
        @JsonDeserialize(using = StringValueDeserializer.class)
        private String smsId;
    
        private String type;
    
        private String username;
        .... getter and setter
    }
    

Good luck!

2 of 3
4

You can also use the JsonPath library to navigate through json:

String json =  restTemplate.exchange(URL_GET,HttpMethod.GET,request, String.class);
DocumentContext document = JsonPath.parse(content, json);
List<User> users = document.read("$.return.*", new TypeRef<List<User>>() {});
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ http client-side โ€บ resttemplate post request with json
RestTemplate Post Request with JSON | Baeldung
March 17, 2024 - The postForObject() method returns the response body as a String type. We can also return the response as a Person object by setting the responseType parameter: Person person = restTemplate.postForObject(createPersonUrl, request, Person.class); ...