I'm getting txt file from resource folder(Spring).
and created the File
File file = new File(classLoader.getResource("files/example.txt").getFile());
And I want to convert this file to JsonObject file.
I'm getting txt file from resource folder(Spring).
and created the File
File file = new File(classLoader.getResource("files/example.txt").getFile());
And I want to convert this file to JsonObject file.
read the content of file using inputstream, then convert the stream to string.. use google gson json library to convert string to json: http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html
You could also use Jackson for this. Jackson is one of the most complete JSON libraries around.
If you are using Maven, just include these dependencies:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
Then you can create an ObjectMapper instance with which you can create a JsonNode (similar to JsonObject) in this way:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(in); // create a tree structure from the JSON
You can do whatever you want with this JsonNode:
jsonNode.fields().forEachRemaining(entry -> {
if(entry.getKey().endsWith(".ID")) {
entry.setValue(new TextNode(UUID.randomUUID().toString()));
}
});