Read JSON file, convert to string in Java

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?

You can follow these steps to move the JSON string to a resources folder and read it from there using JAVA:

  1. Create a resources folder in your project if it doesn’t exist already.
  2. Move the JSON string to a new file in the resources folder with the “.json” extension (e.g. “product.json”).
  3. Load the JSON file from the resources folder using the ClassLoader.getResourceAsStream() method.
  4. Read the contents of the JSON file using a BufferedReader and StringBuilder.
  5. 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");