0

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.

min moica
  • 139
  • 2
  • 12
  • 3
    Possible duplicate of [What’s the best way to load a JSONObject from a json text file?](https://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file) – Krzysztof Mazur Nov 29 '17 at 08:18

2 Answers2

0

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

vaibhav
  • 3,929
  • 8
  • 45
  • 81
0

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()));
    }
});
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76