我正在学习 Spring Boot,我知道如何从资源目录中读取 JSON 文件,但我想获取特定数据,而不是整个数据。 如 localhost:8080/user 返回用户名。
下面是我当前的代码
package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class HelloWorld {
@Value("classpath:json/test.json")
private Resource resourceFile;
@RequestMapping("/")
Resource home() {
return resourceFile;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(HelloWorld.class, args);
}
}
我想读取 test.json 文件中的特定数据。请给我一些建议或步骤。谢谢
最佳答案
一如既往,有几种可能的方法。
除了手动解析和提取方法( How do I load a resource and use its contents as a string in Spring )之外,您还可以尝试更高级的方法并使用像 jackson-databind 这样的库( https://github.com/FasterXML/jackson-databind )。
假设您的资源中存在此 json 对象:
{
"foo" : {
"bar" : 42
}
}
并且 Jackson ObjectMapper 已经注入(inject):
@Autowired
private ObjectMapper objectMapper;
选项 1:使用 JsonNode 的通用方法
@Autowired
ObjectMapper objectMapper;
@RequestMapping("/")
JsonNode home() throws IOException {
JsonNode jsonNode = objectMapper.readTree(resourceFile.getFile());
return jsonNode.get("foo").get("bar");
}
选项 2:https://github.com/FasterXML/jackson-databind#1-minute-tutorial-pojos-to-json-and-back
关于java - Spring boot,如何从json文件读取特定对象,我需要什么注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52930697/