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
.
{
"name": "Niccolo Bargen",
"age": 28,
"Role": "Engineer"
}
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"));
}
🔍. Similar posts
The Simple Way to Run a Long Docker Command in Multiline
14 Jan 2025
How to Hard Reset Your Git Repository to 10 Minutes Ago
04 Sep 2024
How to Easily Generate a Java Project Using Maven Command
04 Sep 2024