12

I have this JSON string hardcoded in my code.

String json = "{\n" +
              "    \"id\": 1,\n" +
              "    \"name\": \"Headphones\",\n" +
              "    \"price\": 1250.0,\n" +
              "    \"tags\": [\"home\", \"green\"]\n" +
              "}\n"
;

I want to move this to resources folder and read it from there, How can I do that in JAVA?

Dilettant
  • 3,267
  • 3
  • 29
  • 29
Subham Saraf
  • 421
  • 2
  • 4
  • 13
  • Do you have constraints on libraries or framework to use? Please add more detail to let the people help you better :) – A. Wolf Jan 10 '20 at 07:55

7 Answers7

15

This - in my experience - is the most reliable pattern to read files from class path.[1]

Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")

It gives you an InputStream [2] which can be passed to most JSON Libraries.[3]

try(InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")){
//pass InputStream to JSON-Library, e.g. using Jackson
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
    String jsonString = mapper.writeValueAsString(jsonNode);
    System.out.println(jsonString);
}
catch(Exception e){
throw new RuntimeException(e);
}

[1] Different ways of loading a file as an InputStream

[2] Try With Resources vs Try-Catch

[3] https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

Hint: Don't try to use this method from within a parallelStream or similar. It will result in an exception.

jschnasse
  • 8,526
  • 6
  • 32
  • 72
  • 1
    just wrote this created jsonNode as string. json = mapper.writeValueAsString(jsonNode); Thanks – Subham Saraf Jan 10 '20 at 08:52
  • This does not work in an Enum initializer block, but replacing the try resource with `InputStream json = getClass().getClassLoader().getResourceAsStream(templateFile)` works in that case. – Nyefan Dec 31 '21 at 19:44
11

Move json to a file someName.json in resources folder.

{
  id: 1,
  name: "Headphones",
  price: 1250.0,
  tags: [
    "home",
    "green"
  ]
}

Read the json file like

File file = new File(
        this.getClass().getClassLoader().getResource("someName.json").getFile()
    );

Further you can use file object however you want to use. you can convert to a json object using your favourite json library.

For eg. using Jackson you can do

ObjectMapper mapper = new ObjectMapper();
SomeClass someClassObj = mapper.readValue(file, SomeClass.class);
Smile
  • 3,832
  • 3
  • 25
  • 39
  • Please note that this approach won't work if you build your code into .jar. Use reading through input stream (for example, see the answer to this question by @jschnasse https://stackoverflow.com/a/59677244/1559962) – Adomas Dec 30 '21 at 18:53
  • elegant way of using it @Smile – anand krish Mar 09 '23 at 13:41
10

There are many possible ways of doing this:

Read the file completely (only suitable for smaller files)

public static String readFileFromResources(String filename) throws URISyntaxException, IOException {
    URL resource = YourClass.class.getClassLoader().getResource(filename);  
    byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));  
    return new String(bytes);  
}

Read in the file line by line (also suitable for larger files)

private static String readFileFromResources(String fileName) throws IOException {
    URL resource = YourClass.class.getClassLoader().getResource(fileName);

    if (resource == null)
        throw new IllegalArgumentException("file is not found!");

    StringBuilder fileContent = new StringBuilder();

    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new FileReader(new File(resource.getFile())));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            fileContent.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return fileContent.toString();
}

The most comfortable way is to use apache-commons.io

private static String readFileFromResources(String fileName) throws IOException {
    return IOUtils.resourceToString(fileName, StandardCharsets.UTF_8);
}
tgallei
  • 827
  • 3
  • 13
  • 22
4

Pass your file-path with from resources:

Example: If your resources -> folder_1 -> filename.json Then pass in

String json = getResource("folder_1/filename.json");
public String getResource(String resource) {
        StringBuilder json = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource)),
                            StandardCharsets.UTF_8));
            String str;
            while ((str = in.readLine()) != null)
                json.append(str);
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("Caught exception reading resource " + resource, e);
        }
        return json.toString();
    }
papaya
  • 1,505
  • 1
  • 13
  • 26
1

There is JSON.simple is lightweight JSON processing library which can be used to read JSON or write JSON file.Try below code

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try (Reader reader = new FileReader("test.json")) {

        JSONObject jsonObject = (JSONObject) parser.parse(reader);
        System.out.println(jsonObject);


    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }  
0
try(InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.MessageInput)){
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readValue(inputStream ,
                    JsonNode.class);
            json = mapper.writeValueAsString(jsonNode);
        }
        catch(Exception e){
            throw new RuntimeException(e);
        }
Subham Saraf
  • 421
  • 2
  • 4
  • 13
0

Reading the json file and converting into object using Jackson Mapper.

  public OldPromotionElements parseOldElements()
{
    File file = new File(this.getClass().getClassLoader().getResource("Test.json").getFile());
   try {
      OldPromotionElements oldPromotionElements;
      ObjectMapper objectMapper= new ObjectMapper();
      oldPromotionElements = objectMapper.readValue(file, OldPromotionElements.class);
    }
   catch (Exception e) {
         System.out.println(e.printStackTrace());
    }
 return oldPromotionElements;
 }

reference link

anand krish
  • 4,281
  • 4
  • 44
  • 47