简体   繁体   中英

Java - Get one item from ResponseEntity List

My ResponseEntity returns a <List> , I only want to access one item in the list but the .getBody() method returns all the data.

RestTemplate restTemplate = new RestTemplate();
ResponseEntity <List> result = restTemplate.getForEntity(uri, List.class);
LOGGER.info(result.getBody());

The result looks something like this:

[{name: data, id: data}]

I want to get the id .How do I return a specific item from the list without using an index.

The body will contain the whole response body, to get a single object, you need to change the service to return only a single object.

If you can't do that, create a simple java stream to return first element.

yourList.stream().filter(element -> --any condition here if needed--).findFirst().map(item -> item.id).orElse(null)

To get the list create object with those 2 fields, id and String.

Rest call would be List yourList = asList(restTemplate.getForObject(url, YourObject[].class));

Your response is [{name: data, id: data}] that means list of object {name: data, id: data} .

Now the Java class will

public class ResponseItem{

    private String name;
    private int id;

    // getter
    // setter
}

Your Rest caller code will like bellow:

List<ResponseItem> response=new ArrayList<>();

RestTemplate restTemplate = new RestTemplate();
ResponseEntity <?> result = restTemplate.getForEntity(uri, response.getClass());
LOGGER.info(result.getBody());

Now you have the list of items. Just cast the result.getBody() with List<ResponseItem> . If you want just id then comment out the id field from ResponseItem class

List<Integer> ids=new ArrayList<>();

        for (ResponseItem item:result
             ) {
            ids.add(item.getId());
        }

Now you have only id field into the ids list

Hope this will help you

Thanks :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM