How to read json file from resource folder in spring boot

To read a JSON file from the resource folder in Spring Boot, you can use the ResourceLoader provided by the framework. The ResourceLoader allows you to access resources (such as files) within the classpath or within the resource folder easily.

Here is an example of how to read a JSON file from the resource folder:


import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

@Component
public class JsonReader {
    
    private final ResourceLoader resourceLoader;
    
    public JsonReader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    
    public MyObject readJsonFile(String fileName) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + fileName);
        
        ObjectMapper mapper = new ObjectMapper();
        MyObject myObject = mapper.readValue(resource.getInputStream(), MyObject.class);
        
        return myObject;
    }
}

// MyObject is the class representing your JSON object

  

In this example, the readJsonFile method reads the JSON file with the given fileName from the resource folder. The method first creates a Resource object using the ResourceLoader and the given file name. The ResourceLoader is autowired into the JsonReader component. The classpath: prefix in the resource path tells Spring Boot to look for the file within the resource folder. The resource.getInputStream() returns an input stream for reading the file.

Then, an ObjectMapper is used to deserialize the JSON content from the input stream into an instance of the MyObject class. The MyObject class should be defined according to the structure of your JSON file. You can customize the MyObject class to match the JSON structure exactly or to only include the fields you are interested in.

Finally, the MyObject instance is returned.

Leave a comment