【问题标题】:Write data in JSON file in right form JAVA以正确的 JAVA 格式将数据写入 JSON 文件
【发布时间】:2017-06-03 03:12:42
【问题描述】:

我对 JSON 中数据输入的形式有疑问。

我在 json 文件中单击按钮保存数据,但输出错误。我该如何解决这个问题,以便新数据集位于逗号之后?

JSONObject json = new JSONObject();
File filename = new File("dbsettings.json");

json.put("driver", textFieldDriver.getText());
json.put("url", textFieldURL.getText());
json.put("scheme", textFieldscheme.getText());          
json.put("name", textFieldDBname.getText());

try {
    System.out.println("Writting Data into JSONfile ...");
    System.out.println(json);
    FileWriter jsonFileWriter = new FileWriter(filename.getAbsoluteFile(), true);
    jsonFileWriter.write(json.toJSONString());
    jsonFileWriter.flush();
    jsonFileWriter.close();
    System.out.println("Done!");

} catch (IOException e) {
    e.printStackTrace();
}
JOptionPane.showMessageDialog(
    null, "Save Data successful", "Information", JOptionPane.INFORMATION_MESSAGE
);
setVisible(false);

这是我的输出:

[{
    "driver": "oracle.jdbc.driver.OracleDriver",
    "url": "dburl1",
    "scheme": "myscheme1",
    "name": "mydbname1"
},{
    "driver": "oracle.jdbc.driver.OracleDriver",
    "url": "myurl",
    "scheme": "myscheme",
    "name": "mydbname"
}]{"scheme":"test3","name":"test4","driver":"test1","url":"test2"}

请帮帮我!

【问题讨论】:

  • 这不是您的实际代码吗?其他 2 个 db 条目来自哪里?
  • 另外两个存在于 JSON-File 中,它们是默认的 db。

标签: java json formatting dataset


【解决方案1】:

问题在于您的 FileWriter 对象并具有 true。这意味着它会附加到文件。如果您想正确地将 JSON 对象添加到文件中,我建议您首先从文件中读取所有 JSON 对象。然后将它们存储在列表中,并将程序中的任何新条目附加到列表中。完成程序后,循环收集的JSON对象列表并覆盖您通过所有新的和旧的JSON对象读取的文件。

程序启动时,从“dbsettings.json”中读取数据并将所有这些 JSON 对象存储在某种数据结构中。如果您需要根据某些键在程序稍后在程序中找到JSON对象,则ArrayList将工作或可能是HashMap。

然后,随着程序运行,您正在从新的JSON对象上接收来自用户的输入,只需将它们添加到数据收集中。不要在每次获得新文件时将它们写入文件。当用户干净地退出该程序时,我建议仅使用集合中的所有JSON对象覆盖文件。这样您就可以确保您的数据在每次启动程序时都是正确的 JSON 格式。唯一的缺点是,如果程序意外退出,则丢失在程序运行期间输入的所有数据。

其他更少的最佳解决方案是通过每次从用户获取数据,除了您上面的所有内容。

//for JSON you want to output them like "[json0, json1,json2,... etc]"
FileWriter jsonFileWriter = new FileWriter(filename.getAbsoluteFile());
jsonFileWriter.write("[")
for(int i = 0; i < jsonDataStructure.size(); i++)
{
    jsonFileWriter.write(jsonDataStructure.get(i).toJSONString());
    if(i + 1 != jsonDataStructure.size())
      jsonFileWriter.write(",");
}
jsonFileWriter.write("]");
jsonFileWriter.flush();
jsonFileWriter.close();

【讨论】:

  • 我读出了 json 文件并将它们写入一个数组列表。之后添加新模型。 System.out.println(models) 显示模型的名称。如何使用ArrayList及其属性编写新的JSON文件? span>
  • 我添加了一个基本循环,用于使用数组列表输出JSON对象作为我的数据结构@deli_gicik span>
  • 我得到它!非常感谢!
猜你喜欢
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
相关资源
最近更新 更多