简体   繁体   English

如何从 Spring 引导中的资源中读取 JSON 文件

[英]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 ClassPathResourceClassPathResource

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.copyInputStream复制到临时文件

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.

相关问题 在 Spring Boot 中从 resources 文件夹中读取文件 - Read file from resources folder in Spring Boot 如何在Java Spring Boot中读取保存在Resources中的文件 - How to read a file saved in Resources in Java Spring Boot 如何从资源中读取 Json 文件 - How to read the Json file from Resources 如何在 Spring Boot 中读取具有给定 URL 的 JSON 文件? - How to read a JSON file with a given URL in Spring Boot? Spring Boot,如何从json文件读取特定对象,我需要什么注释? - Spring boot, how to read particular object from json file, what annotation do I need? Spring 在 docker 上启动无法从资源中读取属性文件,但是可以在没有 Docker 的情况下使用 Z93F725A4jar423D21C28 - Spring boot on docker not able to read a property file from resources, but the can without Docker with java -jar @ServiceActivator 如何在 Spring Boot 中从属性文件中读取 inputChannel? - @ServiceActivator How to read inputChannel from property file in spring boot? 如何在spring boot中从属性文件中读取正则表达式模式 - How to read the regex pattern from property file in spring boot 如何在spring boot中从属性文件中读取限定符? - How to read Qualifier from property file in spring boot? Spring Boot - 如何从file.conf中读取环境变量 - Spring Boot - How to read environment variables from file.conf
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM