如何将数据从文本字段保存到json文件?

时间:2020-04-27 13:29:04

标签: java json swing user-interface

如何保存文本字段中的数据。例如我想得到这个:

[
  {
      "Patient": {
      "name": "John",
      "surname": "Cena"

      }
    },
  {
  "Patient2": {
    "name": "Roger",
    "surname": "Federer"
  }
  }
]

这是我的尝试:

JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());

try (FileWriter Data = new FileWriter("Data.JSON")) {
    Data.write(obj.toJSONString());
    Data.write(obj1.toJSONString());
    } catch (IOException e1) {
        e1.printStackTrace();
    }

但是我没有得到“ Patient2”,如果我按保存按钮而不是添加新的患者,它将覆盖我的第一位患者。

1 个答案:

答案 0 :(得分:0)

您应该使用JSONArray存储多个JSONObject实例:

// build object
JSONObject obj = new JSONObject();
obj.put("name",    field1.getText());
obj.put("surname", field2.getText());

// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);

// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name",    "Roger");
obj1.put("surname", "Federer");

// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);

// create array and add both patients
JSONArray arr = new JSONArray();

arr.put(patient);
arr.put(patient1); 

try (FileWriter Data = new FileWriter("Data.JSON")) {
    Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
     e1.printStackTrace();
}

此代码生成JSON:

[
    {
        "patient": {
            "surname": "Doe",
            "name": "John"
        }
    },
    {
        "patient1": {
            "surname": "Federer",
            "name": "Roger"
        }
    }
]