java - 从 Java Android 中的嵌套 JSON 对象获取数据
问题描述
如何使用 JSONOBJECT 获取“字段”对象 0、1、2、3、4 以及每个对象的“名称”对象字符串
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
这就是我尝试做的
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
但问题是,它给了我对象 null 的值,例如 [value 4 is null] 因为字段的第一个对象中没有 4 的对象。请帮我解决这个问题,感谢您的回答谢谢:)
解决方案
您可以使用keys()
json 对象的迭代器并在其上循环使用while (keys.hasNext())
对于您的示例,它看起来像这样:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
推荐阅读
- javascript - Cypress 与 OpenLayers - 如何模拟 ctrl + 鼠标拖动
- wpf - 使用 MVVM WPF 在树视图中添加、重命名、删除项目
- javascript - 获取 blob 视频并通过 html 提交
- html - Gmail - HTML 类和样式标签在表格中被删除
- c# - 为多个标签生成数据透视表
- c# - File.ReadLines 与 StreamReader.ReadLine
- python - 在 Python 中使用列表连接和排序数组
- php - 用于检测手势的图像比较
- css - 如何使侧边栏滚动 Bootstrap 4
- javascript - Angular - 根据真/假复选框元素显示表格元素