【发布时间】:2022-01-22 10:04:32
【问题描述】:
以下 JSON 对象(名为 json_object 的变量)由两个值组成
- peripheral_devices
- peripheral_tests
都是数组:
{
"peripheral_devices": [
{
"_id": 1,
"active": -1,
"battery": "63",
"bt_firmware_version": "btv1.7.777",
"configured": 0,
"connected": 0,
"consumer_id": 22,
"create_date": 1635807323224,
"device_id": 72,
"discovered": 0,
"firmware_version": "v3.14",
"hardware_version": "null",
"icon": "icon_device_bp5",
"last_connect_date": 1640023710420,
"mac_address": "8C:DE:52:41:FC:57",
"model": "BP5 41FC57",
"name": "BP5",
"other_id": "-1",
"paired": -1,
"type_id": 1,
"update_date": 1635807323224,
"user_id": 13
},
{
"_id": 3,
"active": -1,
"battery": "90",
"bt_firmware_version": "1.0.0",
"configured": -1,
"connected": 0,
"consumer_id": 22,
"create_date": 1635807323239,
"device_id": 72,
"discovered": 0,
"firmware_version": "1.0.0",
"hardware_version": "5.0.0",
"icon": "icon_device_hs2s",
"last_connect_date": 1640022147928,
"mac_address": "00:4D:32:0C:B7:2C",
"model": "HS2S 11070",
"name": "HS2S",
"other_id": "-1",
"paired": -1,
"type_id": 3,
"update_date": 1635807323239,
"user_id": 13
}
],
"peripheral_tests": [
{
"_id": 199,
"consumer_id": 22,
"create_date": 1640020949760,
"end_date": 1640020949078,
"mood_id": -1,
"notes": "",
"start_date": 1640020939533,
"status_id": 1,
"type_id": 2,
"update_date": 0,
"user_id": -99
},
{
"_id": 198,
"consumer_id": 22,
"create_date": 1640020904183,
"end_date": -1,
"metric_bps": {,
"mood_id": -1,
"notes": "",
"start_date": 1640020863742,
"status_id": 1,
"type_id": 1,
"update_date": 0,
"user_id": -99
},
{
"_id": 197,
"consumer_id": 22,
"create_date": 1640020834664,
"end_date": 1640020828741,
"mood_id": -1,
"notes": "",
"start_date": 1640020822580,
"status_id": 1,
"type_id": 3,
"update_date": 0,
"user_id": -99
}
]
}
并派生如下:
JSONObject json_object = new JSONObject(post_data);
使用org.json.JSONArray.JSONArray:
JSONArray peripheral_devices = json_object.getJSONArray("peripheral_devices");
按预期工作,从json_object 解析一个 json 数组。但是,使用相同的技术来获取对象中的第二个数组不会:
JSONArray json_tests = new JSONArray("peripheral_tests");
抛出异常:
A JSONArray text must start with '[' at 1 [character 2 line 1]
为什么?我不明白什么?
【问题讨论】:
-
我认为您的假设,即
json_object已经是typeof JSONObject可能是错误的......因为除非有根JSONObject的句柄,否则可能无法访问嵌套的JSONArray。 ...new关键字 NEVER 是吸气剂。 -
@MartinZeitler - 是的,我已经编辑了我的帖子,展示了它是如何派生的。为什么你会认为不是?
-
@MartinZeitler - 感谢您发现我忽略的内容 - 我实际上并没有使用 json_object 来获取数组!哎呀,如果你愿意回答 - 我会给你信用。