如何将txt文件转换为jsonObject?

时间:2017-11-29 08:15:55

标签: json spring file

我从资源文件夹(Spring)获取txt文件 并创建了文件
File file = new File(classLoader.getResource(“files / example.txt”)。getFile());

我想将此文件转换为JsonObject文件。

2 个答案:

答案 0 :(得分:0)

使用inputstream读取文件内容,然后将流转换为字符串..使用google gson json库将字符串转换为json: http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html

答案 1 :(得分:0)

您也可以使用Jackson。 Jackson是最完整的JSON库之一。

如果您使用的是Maven,只需包含这些依赖项:

<!-- 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>

然后您可以创建一个ObjectMapper实例,您可以用这种方式创建一个JsonNode(类似于JsonObject):

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(in); // create a tree structure from the JSON

您可以使用此JsonNode执行任何操作:

jsonNode.fields().forEachRemaining(entry -> {
    if(entry.getKey().endsWith(".ID")) {
        entry.setValue(new TextNode(UUID.randomUUID().toString()));
    }
});
相关问题