java - 将嵌套 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);
我该如何解决这个问题?
谢谢
解决方案
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);
也可以看看:
推荐阅读
- html - 限制在 div 标签中存在的特定标签上应用 CSS 属性
- selenium - Selenium 节点 JavaScript 禁用下载
- html - ng-if 条件不与 Angular JS 中的 ng-repeat 绑定
- firebase - 在 Firestore 中等于或为空的地方
- python - 如何将文件从 React/Next.js 客户端 UI 发送到 Node 服务器和 Flask 服务旁边
- python - 如何在熊猫数据框中的列内创建列?
- vb.net - String.Split() 删除分隔符
- flutter - 无法从 Flutter Web 读取 Firestore 中的数据(适用于 iOS 和 android)
- installation - grub2:在 grub.cfg 中为 linux 内核和 initrd 映像指定 http 位置
- matlab - 矩阵接近奇异或严重缩放的投资组合排序