I want to move this JSON string from my code to a resources folder and read it from there using JAVA.
String json = "{\n" +
" \"id\": 1,\n" +
" \"name\": \"Headphones\",\n" +
" \"price\": 1250.0,\n" +
" \"tags\": [\"home\", \"green\"]\n" +
"}\n"
;
How can I do that?
Arvel45
(Arvel Little)
2
You can follow these steps to move the JSON string to a resources folder and read it from there using JAVA:
- Create a resources folder in your project if it doesn’t exist already.
- Move the JSON string to a new file in the resources folder with the “.json” extension (e.g. “product.json”).
- Load the JSON file from the resources folder using the ClassLoader.getResourceAsStream() method.
- Read the contents of the JSON file using a BufferedReader and StringBuilder.
- Close the BufferedReader and return the JSON string.
Here’s the code to do that:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JsonReader {
public static String readJsonFile(String fileName) {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = JsonReader.class.getClassLoader().getResourceAsStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
To use this code, simply call the readJsonFile() method with the name of your JSON file (without the resources folder path):
String json = JsonReader.readJsonFile("product.json");