user2047296
user2047296

Reputation: 315

Mapping nested JSON to a Java POJO

I am having difficulties mapping a nested JSON response to a POJO using Jackson. At the moment the values in the Users class return as null.

JSON:

{
"users": [
    {
        "username": "johnSmith123",
        "email": "[email protected]",
        "birthday": "1989-10-23"
    }
]
}

POJO:

public class Users {

  @JsonProperty("username")
  public String username;
  @JsonProperty("email")
  public String email;
  @JsonProperty("birthday")
  public String birthday;

}

Controller method:

private ObjectMapper mapper = new ObjectMapper();

ResponseEntity<String> response = restTemplate.exchange(
        accountUrl, HttpMethod.GET, entity, String.class);

Users user = mapper.readValue(response.getBody(), Users.class);

How could I go about resolving this?

Thanks

Upvotes: 3

Views: 6871

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38625

Users JSON Object is wrapped in JSON Array which is wrapped in root JSON Object. You need to use collections types:

TypeReference<Map<String, List<Users>>> usersType = new TypeReference<Map<String, List<Users>>>() {};
Map<String, List<Users>> wrappedUsers = mapper.readValue(body, usersType);
List<Users> users = wrappedUsers.values().stream().flatMap(Collection::stream).collect(Collectors.toList());

Or create wrapper class:

class UsersHolder {
    public List<Users> users;

    //getters, setters
}

which you can use as:

UsersHolder wrappedUsers = mapper.readValue(body, UsersHolder.class);
System.out.println(wrappedUsers.users);

See also:

Upvotes: 4

Related Questions