首页 > 解决方案 > 如何根据 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 版本。

标签: javajsonspring-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);
}

推荐阅读