将包含json对象行的纯文本文件转换为json文件

问题描述 投票:0回答:1

[[techno:java spring boot]

有一个.txt文件,其中包含:

{ "foo": "one" }
{ "bar": "two" }
  1. 在Java中,有没有办法像这样转换json中的内容文件? :
[
{ "foo": "one" },
{ "bar": "two" }
]
  1. 或通过循环获取每一行
loop(contentFile as line) {
 // line = { "foo": "one" }
}
java json spring-boot string-parsing
1个回答
0
投票

您可以遍历每行,然后尝试将行的内容解析为JSONObject,然后将所有这些JSONObject收集到JSONArray中,然后将序列化的Array写入json文件中。

例如,使用json-simple或javax.json。


0
投票

您可以像下面这样逐行读取Java文件:

try {
    BufferedReader reader reader = new BufferedReader(new FileReader(path-to-json-file));
    String line = reader.readLine(); //here line = { "foo": "one" }
    while (line != null) {
          //do required opertaion and read next line
            line = reader.readLine();
        }
            reader.close();
    } catch (IOException e) {
            e.printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.