我需要用 Java 決議一個 JSON 字串。我正在使用 JSONObject 來決議字串并獲取物件。我不知道如何在不知道鍵的情況下遍歷三重陣列。
這是字串形式的 JSON:
{ "version": "0.8.0", "generator": "vzlogger", "data": [ { "uuid": "d495a390-f747-11e0-b3ca-f7890e45c7b2", "last": 0, "interval": -1, "protocol": "s0" }, { "uuid": "a76ffbb0-5fcb-11ec-afdd-597654871263", "last": 1639902960610, "interval": 0, "protocol": "d0", "tuples": [ [ 1639902960610, 33067 ] ] } ]
我需要遍歷每個資料并為每個條目獲取 uuid。我需要為每個 uuid 獲取元組。例如
uuid a76ffbb0-5fcb-11ec-afdd-597654871263
first tuples 1639902960610
second tuples 33067
...
陣列中有 50 個 uuid,在上面的示例中,我只復制了第一個。
這是我的代碼:
JSONObject obj = http.getResponseJSON();
JSONArray arr = obj.getJSONArray("data"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i ){
String uuid = arr.getJSONObject(i).getString("uuid");
if (arr.getJSONObject(i).has("tuples")) {
JSONArray tuples = arr.getJSONObject(i).getJSONArray("tuples");
log.println("UUID: " uuid "CNT: " tuples.length());
for (int j = 0; j < arr.length(); j ){
String tuple = tuples.getJSONObject(j).get ... HELP ... THERE IS NO KEY ....
}
}
}
uj5u.com熱心網友回復:
您在元組欄位中嵌套了陣列。所以首先
- 遍歷外部陣列
- 然后對于每個索引,遍歷內部陣列并直接列印值。
這是作業代碼
if (arr.getJSONObject(i).has("tuples")) {
JSONArray outerTuples = arr.getJSONObject(i).getJSONArray("tuples");
System.out.println("UUID: " uuid);
for (int k = 0; k < outerTuples.length(); k ) {
JSONArray innerTuples = outerTuples.getJSONArray(k);
for (int j = 0; j < innerTuples.length(); j ) {
System.out.println(innerTuples.get(j));
}
}
}
uj5u.com熱心網友回復:
方法 1:使用 for 回圈:這是最簡單的方法,我們只需要使用 for 回圈,其中計數器變數逐個訪問每個元素。
匯入 java.io.*; 類 GFG {
public static void main(String args[]) throws IOException
{
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int i, x;
// iterating over an array
for (i = 0; i < ar.length; i ) {
// accessing each element of array
x = ar[i];
System.out.print(x " ");
}
}
}
方法 2 使用 for each 回圈:For each 回圈優化代碼,節省打字和時間。
匯入 java.io.*; 類 GFG {
public static void main(String args[]) throws IOException
{
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int x;
// iterating over an array
for (int i : ar) {
// accessing each element of array
x = i;
System.out.print(x " ");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/386271.html
