以正确的JAVA格式在JSON文件中写入数据

以正确的JAVA格式在JSON文件中写入数据,java,json,formatting,dataset,Java,Json,Formatting,Dataset,我对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",

我对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"}

请帮帮我

问题在于您的FileWriter对象是否正确。这意味着它将附加到文件中。如果您想正确地将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,您希望将其输出为“[json0、json1、json2……等等”
FileWriter jsonFileWriter=新的FileWriter(filename.getAbsoluteFile());
jsonFileWriter.write(“[”)
对于(int i=0;i
这不是您的实际代码,是吗?其他2个db条目来自哪里?另外两个存在于JSON文件中,它们是默认的db。我读取JSON文件并将它们写入arraylist。之后,添加新模型。System.out.println(模型)向我显示模型的名称。如何使用arraylist及其属性编写一个新的json文件?我添加了一个基本的循环,用于使用数组列表作为数据结构输出json对象@deli_gicikI get it!谢谢!