Read json file from resources and convert it into json string in JAVA

We Are Going To Discuss About Read json file from resources and convert it into json string in JAVA . So lets Start this Java Article.

Read json file from resources and convert it into json string in JAVA

  1. Read json file from resources and convert it into json string in JAVA

    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]

  2. Read json file from resources and convert it into json string in JAVA

    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]

Solution 1

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

Original Author Of This Content

Solution 2

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);
}

Original Author Of This Content

Solution 3

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);

Original Author Of This Content

Solution 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();
    }

Original Author Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment