'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?
Solution 1:[1]
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);
}
Solution 2:[2]
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
Solution 3:[3]
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);
}
Solution 4:[4]
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);
Solution 5:[5]
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();
}
Solution 6:[6]
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();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Subham Saraf |
| Solution 2 | DV82XL |
| Solution 3 | tgallei |
| Solution 4 | |
| Solution 5 | papaya |
| Solution 6 |
