0

I am currently writing a SpringBoot application that retrieves a JSON array from an external API. The part of the JSON I need looks like:

{
"users": [
    "id": 110,
    "name": "john"
  ]
}

In my Controller I am doing the following:

 ResponseEntity<Users> response = restTemplate
    .exchange(url, headers, Users.class);

return response

I then have a Users class that looks like:

@JsonProperty("id")
public String id;
@JsonProperty("name")
public string name;

How can I access the information inside the JSON array?

Thanks in advance.

2 Answers 2

1

Instead of loading into a POJO based on your return type you need to accept list of Users.

You cannot accept List of user class in ResponseEntity you need to first cast into object class.

ResponseEntity<Object> response = restTemplate .exchange(url, headers, Object.class);

Then you need to convert it into list of users.

List<Users> usersList = (List<Users>) response.getBody();

Sign up to request clarification or add additional context in comments.

Comments

1

The JSON you posted above is not correct. It needs to be:

{
   "users": [
       {
          "id": 110,
          "name": "john"
       }
    ]
}

and whatever object is used needs a list of Users.

The other thing is you restTemplate call is wrong, you are expecting the call to return ResponseEntity<Opportunities> class yet when in your restTemplate you are giving it the User class and that will return ResponseEntity<User> instead

1 Comment

Sorry these were editing mistakes when posting the code. They do match what you have posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.