Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
Subham Saraf Avatar asked Jan 10 '20 07:01

Subham Saraf


People also ask

How do I read a JSON file as a string?

Take input from the user for the location and name. Create convertFileIntoString() In the convertFileIntoString() method, we use the get() method of the Paths class to get the file data. We use the readAllBytes() method of the Files class to read bytes data of the JSON files as a string.

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


6 Answers

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

like image 149
jschnasse Avatar answered Nov 03 '22 07:11

jschnasse


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);
}
like image 45
tgallei Avatar answered Nov 03 '22 07:11

tgallei


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);
like image 31
Smile Avatar answered Nov 03 '22 08:11

Smile


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();
    }
like image 31
papaya Avatar answered Nov 03 '22 07:11

papaya


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();
    }  
like image 30
Chetan pothkar Avatar answered Nov 03 '22 08:11

Chetan pothkar


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);
        }
like image 23
Subham Saraf Avatar answered Nov 03 '22 08:11

Subham Saraf