- Foreword
In the springboot project, we often need to obtain configuration files, including but not limited to YML, XML, Properties, JSON and other types of files; Properties and YML are generally used as the main configuration files of the project and can be read by annotating @Value; so how should the JSON file be What about reading? - Implement reading of JSON files (the example JSON is a collection of objects)
2.1 Development environment path
2.2 Packaging environment path
2.3 Directly upload the detailed code
private final ResourceLoader resourceLoader;
@Autowired
public SxxxxxService(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
// read JSON file content to string
String jsonString = null;
Resource resource = resourceLoader.getResource("classpath:fxxxxx.json");
try {
jsonString = new String(toByteArray(resource.getInputStream()), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
JSONArray result = JSONObject.parseArray(jsonString);
/**
* input flowbytebyte array
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try(InputStream in = input){
IOUtils.copy(in, output);
}
return output.toByteArray();
}
2.4 Note that the reference package of Resource is org.springframework.core.io.Resource