【发布时间】:2022-01-05 08:33:30
【问题描述】:
为了创建一个包含以下内容的JSON 文件:
{"Person_0":{"name_0":["name of person_0"],"last name_0":["last name of person_0"],"phone_0":["phone of person_0"],"email_0":["email of person_0"],"address_0":["address of person_0"]}}
{"Person_1":{"name_1":["name of person_1"],"last name_1":["last name of person_1"],"phone_1":["phone of person_1"],"email_1":["email of person_1"],"address_1":["address of person_1"]}}
{"Person_2":{"name_2":["name of person_2"],"last name_2":["last name of person_2"],"phone_2":["phone of person_2"],"email_2":["email of person_2"],"address_2":["address of person_2"]}}
我用 Java 编写了以下代码:
JSONObject mainData;
JSONObject subData;
String[] mainDataString = new String[3];
try {
FileWriter jsonFile = new FileWriter("Json.json");
PrintWriter writer = new PrintWriter(jsonFile);
writer.print("");
for (int personIndex = 0; personIndex < 3; personIndex++) {
mainData = new JSONObject();
subData = new JSONObject();
subData.append("name_" + personIndex, "name of person_" + personIndex);
subData.append("last name_" + personIndex, "last name of person_" + personIndex);
subData.append("phone_" + personIndex, "phone of person_" + personIndex);
subData.append("email_" + personIndex, "email of person_" + personIndex);
subData.append("address_" + personIndex, "address of person_" + personIndex);
mainData.put("Person_" + personIndex, subData);
mainDataString[personIndex] = mainData.toString();
jsonFile.write(mainDataString[personIndex]);
jsonFile.flush();
}
} catch (JSONException e) {
e.printStackTrace();
}
但是,输出如下,JSON 文件中元素的顺序不是我想要的:
{"Person_0":{"email_0":["email of person_0"],"name_0":["name of person_0"],"address_0":["address of person_0"],"last name_0":["last name of person_0"],"phone_0":["phone of person_0"]}}
{"Person_1":{"phone_1":["phone of person_1"],"name_1":["name of person_1"],"email_1":["email of person_1"],"address_1":["address of person_1"],"last name_1":["last name of person_1"]}}
{"Person_2":{"phone_2":["phone of person_2"],"name_2":["name of person_2"],"email_2":["email of person_2"],"last name_2":["last name of person_2"],"address_2":["address of person_2"]}}
代码有什么问题?
P.S.我试过subData.append和subData.put。
【问题讨论】:
-
如果您的意思是对象中属性的顺序(name_、last_name_ 等),那么 JSON 没有任何排序的概念。将其视为一组键值对。只有数组 [ ] 中的元素是有序的。
-
来自 RFC 7159 -JavaScript 对象表示法 (JSON) 数据交换格式:对象是零个或多个名称/值对的无序集合,其中名称是字符串,值是字符串、数字、布尔值、null、对象或数组。
-
为什么顺序如此重要?
-
@LHCHIN ,不重要,只是我认为获取输出顺序混乱的代码有问题...
-
好的!我只是对此感到好奇。因此,正如 Krzysztof Cichocki 回答的那样,JSON 库在序列化/反序列化时不会保持顺序。但是,如果您坚持这样做,仍然有一些方法可以实现。