我想将一个对象数组写入JSON文件。例如:
public class Passanger{
private String name;
private String surname;
}
我想创建对象数组(Passenger [] Passengers)并将其另存为JSON文件 与Gson。 JSON示例:
[
{"name": "jack", "surname": "dere"},
{"name": "adam", "surname": "ered"}
]
答案 0 :(得分:0)
要编写JSON的数据结构,您可以使用例如
public void toFillData() {
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
JSONArray listP = new JSONArray();
//Cycle for passengers
list.add("of_name");
list.add("of_surname");
// To build one passenger like json object
obj.put("passenger", list);
// To add passenger to list of passengers
listP.add(obj);
try {
// Save to file
FileWriter file = new FileWriter(fn);
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
//Print on console
System.out.print(obj);
}