【问题标题】:how to convert txt file to jsonObject?如何将txt文件转换为jsonObject?
【发布时间】:2017-11-29 08:15:55
【问题描述】:

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

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

【问题讨论】:

标签: json spring file


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您也可以为此使用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()));
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2021-07-11
      • 2015-10-30
      • 2011-11-03
      • 2017-08-01
      • 2020-06-11
      • 2018-01-07
      相关资源
      最近更新 更多