In Java Spring Boot, handling JSON files is a common task, especially when dealing with data exchange between applications or storing configuration information. One of the fundamental steps in working with JSON files is reading them as strings for example.
In this blog post, we will explore a simple yet effective method to read a JSON file as a string using Java Spring Boot.
In your src/test/resources
folder of your Spring Boot project, create a file employee.json
.
Now create a simple class to handle the JSON file manipulation.
public class JsonHandler {
public String readFile(String filePath) throws IOException {
return new String(Files.readAllBytes(Paths.get(filePath)));
}
}
Test that we got the correct string from the JSON file. To do so, we can use the Java 15 Text blocks
to create an expected JSON file from our test method.
@Test
void shouldReadJsonFile() throws IOException {
var jsonHandler = new JsonHandler();
String jsonFileExpected = """
{
"name": "Niccolo Bargen",
"age": 28,
"Role": "Engineer"
}""";
assertThat(jsonFileExpected).isEqualTo(jsonHandler.readFile("src/test/resources/employee.json"));
}
Author : Kevin Kouomeu
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium