首页 > 解决方案 > 将嵌套 JSON 映射到 Java POJO

问题描述

我在使用 Jackson 将嵌套的 JSON 响应映射到 POJO 时遇到困难。目前,Users 类中的值返回为 null。

JSON:

{
"users": [
    {
        "username": "johnSmith123",
        "email": "johnSmith123@gmail.com",
        "birthday": "1989-10-23"
    }
]
}

POJO:

public class Users {

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

}

控制器方法:

private ObjectMapper mapper = new ObjectMapper();

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

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

我该如何解决这个问题?

谢谢

标签: javajsonspring-bootjackson

解决方案


Users JSON Object被包裹在JSON Array其中被包裹在 root 中JSON Object。您需要使用集合类型:

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

或者创建包装类:

class UsersHolder {
    public List<Users> users;

    //getters, setters
}

您可以将其用作:

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

也可以看看:


推荐阅读