java - 如何根据 ID Spring Boot 从文件中打印原始 json 对象
问题描述
我在本地有一个包含一些数据的 json 文件。我正在编写一个路径,以便当用户执行 /person/1 时,它只会根据该 ID 从文件中返回该人对象的原始 json。
{
"id": 1,
"name": "Sally",
"age": "12",
"likes": [cats, dogs, rabbits]
},
{
"id": 2,
"name": "jenny",
"age": "22",
"likes": [games, makeup]
}
]
这个想法是当用户访问 localhost:8080/people/1 他们将返回到屏幕上
{
"id": 1,
"name": "Sally",
"age": "12",
"likes": [cats, dogs, rabbits]
}
我尝试使用 PersonDTO,我可以返回每个人,我知道通过一些工作我可以通过 ID 过滤它,但我想要原始数据,而不是通过 DTO 方式获得的更干净的 java/Spring Boot 版本。
解决方案
使用 Gson,试试下面的代码:
@RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonNode> getPeopleInfo(@PathVariable(name = "id") Integer id) throws Exception {
Reader reader = new FileReader(new File("D:\\codes\\gitlab\\response.json"));
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(reader, JsonNode.class);
for (int i = 0; i < jsonNode.size(); i++) {
JsonNode element = jsonNode.get(i);
if (element.get("id").asInt() == id) {
return new ResponseEntity<>(element, HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
推荐阅读
- c# - C# Roslyn 替换方法
- nginx - openResty 写日志头失败
- javascript - 如何更改 ApplePayJS 上显示的价格格式?
- azure - 具有多个设备的基于 Azure 流分析阈值的规则
- r - 如何从R中单个图表中的data.frame中的所有数据制作直方图
- javascript - 如何按顺序对数组内的重复值求和
- css - 当绝对位置时,如何将链接放置在等于部分高度一半的高度?造型工作,但我被告知是错误的。少了什么东西?
- jpa - JPA 和 Sysdate 问题 - 强制接受 Double 数据类型
- mongodb - Mongo 下周二找到
- mongodb - MongoDB 按产品的子类别聚合和分组