如何将textfields中的数据保存到json文件中?

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

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

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

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

这是我的尝试,但我没有得到 "Patient2

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",如果我按下保存按钮而不是添加新的,它就会覆盖我的第一个病人。

java json swing user-interface
1个回答
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"
        }
    }
]
© www.soinside.com 2019 - 2024. All rights reserved.