Java - How to Read JSON File as String
In this post we will look at how to read a JSON file as a String variable in Java. This is sometimes useful, especially in API testing when you want to POST a JSON payload to an endpoint.
You can put the JSON payload in a file, then read the JSON file as a String and use it as the body of a POST request.
Read JSON File as String
Suppose we have a JSON file in the following location:
src/test/resources/myFile.json
{
"name":"David",
"age":30,
"hobbies":["Football","Cooking","Swimming"],
"languages":{"French":"Beginner","German":"Intermediate","Spanish":"Advanced"}
}
Then we can use the following Java code to read the above JSON file as String:
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadJsonAsString {
public static void main(String[] args) throws Exception {
String file = "src/test/resources/myFile.json";
String json = readFileAsString(file);
System.out.println(json);
}
public static String readFileAsString(String file)throws Exception
{
return new String(Files.readAllBytes(Paths.get(file)));
}
}
Output:
{
"name":"David",
"age":30,
"hobbies":["Football","Cooking","Swimming"],
"languages":{"French":"Beginner","German":"Intermediate","Spanish":"Advanced"}
}