Alex Yates
Alex Yates

Reputation: 89

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?

Upvotes: 1

Views: 5430

Answers (2)

Fima Taf
Fima Taf

Reputation: 977

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();

Upvotes: 2

HL&#39;REB
HL&#39;REB

Reputation: 866

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();

Upvotes: 0

Related Questions