【问题标题】:BufferedWriter doesnt write JSON String correctlyBufferedWriter 未正确写入 JSON 字符串
【发布时间】:2017-01-12 23:30:25
【问题描述】:

我编写了一个从网站获取 JSON 文本并对其进行格式化的代码,以便于阅读。我的代码问题是:

public static void gsonFile(){
  try {
    re = new BufferedReader(new FileReader(dateiname));
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    String uglyJSONString ="";
    uglyJSONString = re.readLine();
    JsonElement je = jp.parse(uglyJSONString);  
    String prettyJsonString = gson.toJson(je);
    System.out.println(prettyJsonString);

    wr = new BufferedWriter(new FileWriter(dateiname));
    wr.write(prettyJsonString);

    wr.close();
    re.close();

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

它正确地将其打印到控制台中:http://imgur.com/B8MTlYW.png

但在我的 txt 文件中是这样的:http://imgur.com/N8iN7dv.png

我该怎么做才能正确地将其打印到文件中? (以新行分隔)

【问题讨论】:

  • 抱歉,已编辑。
  • 我的错:这些不是图片,不应该这样发布。它们应该以代码格式的文本形式发布。请通过help center 了解更多信息。

标签: java json string writer


【解决方案1】:

Gson 使用\n 作为行分隔符(可以在newline 方法here 中看到)。

由于记事本不理解\n,您可以使用其他文件编辑器(写字板Notepad++AtomSublime Text)打开结果文件等)或在编写之前将\n 替换为\r\n

prettyJsonString = prettyJsonString.replace("\n", "\r\n");

【讨论】:

    【解决方案2】:

    FileReader 和 FileWriter 是使用平台编码的旧实用程序类。这给出了不可移植的文件。对于 JSON,通常使用 UTF-8。

    Path datei = Paths.get(dateiname);
    re = Files.newBufferedReader(datei, StandardCharsets.UTF_8);
    

    或者

    List<String> lines = Files.readAllLines(datei, StandardCharsets.UTF_8);
    // Without line endings as usual.
    

    或者

    String text = new String(Files.readAllBytes(datei), StandardCharsets.UTF_8);
    

    后来:

    Files.write(text.getBytes(StandardCharsets.UTF_8));
    

    【讨论】:

      【解决方案3】:

      快速搜索后,这个主题可能会派上用场。

      Strings written to file do not preserve line breaks

      另外,像其他人所说的那样在另一个编辑器中打开也会有所帮助

      【讨论】:

        【解决方案4】:

        这是您的文本编辑器的问题。不带文字。它错误地处理换行符。

        我想它期望 CR LF(Windows 方式)符号和 Gson 只生成 LF 符号(Unix 方式)。

        【讨论】:

        • 尝试用另一个编辑器打开它(我知道你可以用notepad++看到空白字符)并检查那里的布局和空白。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-17
        • 1970-01-01
        • 2016-08-21
        • 1970-01-01
        相关资源
        最近更新 更多