简体   繁体   中英

SpringBoot deserialize a JSON array in Java using Jackson

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.

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

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

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