简体   繁体   中英

Returning Value from HTTP Response in Java

I'm having an issue getting a value while using a ResponseEntity. In simplest terms, after making an API call and using

ResponseEntity<String> response = *api call*
String value = response.getBody();

I get as an output

{"value":123456}

However I would like to have the string: value be equal to just 123456 without simply brute forcing it. Any Ideas on how to do so?

Don't use string as the generic of the ResponseEntity object. Create your own object like this:

public class MyResponse {
    private String value;

    public String getValue () {
        return this.value;
    }

    public void setValue (String value) {
        this.value = value;
    }
}

And then use this object like this:

ResponseEntity<MyResponse> response = *api call*
String value = response.getBody().getValue();

The behaviour is normal since your ResponeEntity is wrapping a String.

You should rather use a class that defines an attribute value .

Assuming you have a class MyClass that defines the attribute value (with proper getter), all you have to do is to change your code as follows :

ResponseEntity<MyClass> response = *api call* 

String value = response.getBody().getValue();

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