英文:
how to read nested json list in java?
问题
JSONArray jsonarray = new JSONArray(response);
System.out.println(String.format("JSONArray length => %d", jsonarray.length()));
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj1 = jsonarray.getJSONObject(i);
String name = obj1.getString("name");
int type = obj1.getInt("type");
JSONObject networkUsage = obj1.getJSONObject("networkUsage");
int downloadValue = networkUsage.getInt("download");
System.out.println(name);
System.out.println(type);
System.out.println(downloadValue);
}
英文:
I need to get type value and networkUsage download value and list was dynamic
Json Response was
{
"count": 2,
"devices": [
{
"name": "xyz",
"type": 1,
"subType": 0,
"signalStrength": -37,
"dataUsage": {
"download": 84,
"upload": 84
},
"networkUsage": {
"download": 0,
"upload": 0
},
"speed": {
"download": 0,
"upload": 0
}
},
{
"name": "abcd",
"type": 2,
"subType": 0,
"signalStrength": -37,
"dataUsage": {
"download": 84,
"upload": 84
},
"networkUsage": {
"download": 0,
"upload": 0
},
"speed": {
"download": 0,
"upload": 0
}
}
]
}
I tried this way and got errors.
JSONArray jsonarray = new JSONArray(response);
System.out.println(String.format("JSONArray length => %d", jsonarray.length()));
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj1 = jsonarray.getJSONObject(i);
String name = obj1.getString("name");
int type = obj1.getInt("type");
System.out.println(name);
System.out.println(type);
}
> Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at character 1 at org.json.JSONTokener.syntaxError(JSONTokener.java:496) at org.json.JSONArray.<init>(JSONArray.java:115) at org.json.JSONArray.<init>(JSONArray.java:159) at com.calix.pages.test.main(test.java:91)
答案1
得分: 0
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonarray = jsonobj.getJSONArray("devices");
for (int i = 0; i < jsonobj.getInt("count"); i++) {
JSONObject obj1 = jsonarray.getJSONObject(i);
String name = obj1.getString("name");
int type = obj1.getInt("type");
System.out.println(name);
System.out.println(type);
}
英文:
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonarray = jsonobj.getJSONArray("devices");
for (int i = 0; i < jsonobj.getInt("count"); i++) {
JSONObject obj1 = jsonarray.getJSONObject(i);
String name = obj1.getString("name");
int type = obj1.getInt("type");
System.out.println(name);
System.out.println(type);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论