In this tutorial we will see a simple method to read a JSON file from classpath in Java and Spring-Boot. This will work even when JSON file is packaged and deployed as a spring-boot app or as a Java application.
Get Started:
First you will have to create a Spring-boot project as seen in my previous post using CLI. Then create a REST API which will return a JSON response by reading a JSON file as seen below:
@RestController public class UserProfileRestService { @GetMapping(value = RestConstants.REQUEST_URL, produces = MediaType.APPLICATION_JSON_VALUE) public String getUser(@PathVariable String userId) { return readFromJson(FileConstants.USER_JSON_FILE_NAME); } }
Now create a function that reads the JSON file from the classpath:
public class JsonUtil { private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class); /** * Function returns the JSON String for a give json file. * * @param filename fileName * @return String jsonString */ public static String readFromJson(String filename) { LOG.info("In readFromJson() fileName : " + filename); try { ClassPathResource cpr = new ClassPathResource(filename); byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream()); return new String(bdata, StandardCharsets.UTF_8); } catch (FileNotFoundException e) { LOG.error("Exception in : readFromJson(): File Not Found!!!: " + filename); } catch (IOException e) { LOG.error("Exception in : readFromJson(): IOException!!!: " + e.getMessage()); } return null; } }
Run it as a Java application to display the contents of the json file as seen below:
public class JsonReaderExample { private static final Logger LOG = LoggerFactory.getLogger(JsonReaderExample.class); public static void main(String[] args) { JsonUtil util = new JsonUtil(); String jsonOutput = util.readFromJson(FileConstants.USER_JSON_FILE_NAME); LOG.info("JSON Response: {}", jsonOutput); } }
OUTPUT:
{ "userId": 1, "id": 1, "name": "John", "email": john@techknowbase.com }
Therefore readFromJson() method read a JSON file from classpath under src/main/resources/user.json. That’s all folks. I hope it helps.