[英]How to read JSON file from resources in Spring Boot
Using Spring Boot 2.1.5 Release, have created the following sample Spring Boot Microservice:使用 Spring Boot 2.1.5 Release,创建了以下示例 Spring Boot Microservice:
Maven Project Structure: Maven 项目结构:
MicroService
│
pom.xml
src
│
└───main
│
├───java
│ │
│ └───com
│ └───microservice
│ │
│ └───MicroServiceApplication.java
│
└───resources
│
└───data.json
│
application.properties
Have the following JSON file (inside src/main/resources/data.json):具有以下 JSON 文件(在 src/main/resources/data.json 内):
{"firstName": "John", "lastName": "Doe"}
MicroServiceApplication:微服务应用:
@SpringBootApplication
public class MicroServiceApplication {
@Bean
CommandLineRunner runner() {
return args -> {
String data = FilePathUtils.readFileToString("../src/main/resources/data.json", MicroServiceApplication.class);
System.out.println(data);
};
}
public static void main(String[] args) {
SpringApplication.run(MicroServiceApplication.class, args);
}
}
Throws the following exception:引发以下异常:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
...
Caused by: java.io.IOException: Stream is null
FilePathUtils.java: FilePathUtils.java:
import io.micrometer.core.instrument.util.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class FilePathUtils {
public static String readFileToString(String path, Class aClazz) throws IOException {
try (InputStream stream = aClazz.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IOException("Stream is null");
}
return IOUtils.toString(stream, Charset.defaultCharset());
}
}
}
What am I possibly being doing wrong?我可能做错了什么?
While @Deadpool has provided the answer, I would like to add that when the artifact of spring boot is created there is no such src/main/
folder anymore (you can open the spring boot artifact and make sure by yourself).虽然@Deadpool 提供了答案,但我想补充一点,当创建 spring 引导工件时,不再有这样的src/main/
文件夹(您可以打开 spring 引导工件并自行确保)。
So you can't load resources like this:所以你不能像这样加载资源:
FilePathUtils.readFileToString("../src/main/resources/data.json", MicroServiceApplication.class);
Spring indeed has an abstraction called Resource
that can be used in the application, that can even be injected into the classes / configuration: Spring 确实有一个称为Resource
的抽象,可以在应用程序中使用,甚至可以注入到类/配置中:
@Value("classpath:data/data.json")
Resource resourceFile;
Notice the prefix "classpath" it means that the resource will be resolved from the classpath (read everything properly packaged into the artifact).请注意前缀“类路径”,它意味着资源将从类路径中解析(读取正确打包到工件中的所有内容)。
There is a pretty good Tutorial that can be handy有一个很好的教程,可以很方便
In spring boot project you can use ResourceUtils
在 spring 引导项目中,您可以使用ResourceUtils
Path file = ResourceUtils.getFile("data/data.json").toPath();
or ClassPathResource
或ClassPathResource
String clsPath = new ClassPathResource("data/data.json").getPath();
Sometimes if you are reading different extension file like .graphql
or .mmdb
or .json
you need to read it as InputStream
using spring ResourceLoader
, this article has clear explanation有时,如果您正在读取不同的扩展文件,例如.graphql
或.mmdb
或.json
您需要使用ResourceLoader
将其作为InputStream
读取,这篇文章有明确的解释
@Autowire
private ResourceLoader resourceLoader;
Resource resource =resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
InputStream dbAsStream = resource.getInputStream();
And copy the InputStream
to temp file using Files.copy
并使用Files.copy
将InputStream
复制到临时文件
Files.copy(inputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
You can use the jackson-databind
library.您可以使用jackson-databind
库。
The Jackson ObjectMapper
class ( com.fasterxml.jackson.databind.ObjectMapper
) is one of the simplest way to parse JSON
. The Jackson ObjectMapper
class ( com.fasterxml.jackson.databind.ObjectMapper
) is one of the simplest way to parse JSON
. The Jackson ObjectMapper can parse JSON
from a string, stream or file, and create a Java object or object graph
representing the parsed JSON. The Jackson ObjectMapper can parse JSON
from a string, stream or file, and create a Java object or object graph
representing the parsed JSON. Parsing JSON
into Java objects is also referred to as to deserialize Java objects
from JSON.将 JSON Parsing JSON
为 Java 对象也称为deserialize Java objects
来自 Z70ECD11C18A27BBB8
// create Object Mapper
ObjectMapper mapper = new ObjectMapper();
// read JSON file and map/convert to java POJO
try {
SomeClass someClassObject = mapper.readValue(new File("../src/main/resources/data.json"), SomeClass.class);
System.out.println(someClassObject);
} catch (IOException e) {
e.printStackTrace();
}
and you shoud have jackson-databind
in your .pom
file:你应该在你的.pom
文件中有jackson-databind
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.