這個問題在這里已經有了答案: JSON 字串陣列(無物件),提取資料 (4 個回答) 如何在 Java 中決議 JSON (34 個回答) 5 小時前關閉。
我試圖從一個陣列中獲取所有值,這些值放在 JSON 中。
這是我的 JSON:
{
"greetings": [
"Hello",
"Hi",
"Hey"
]
}
try {
JSONObject json = new JSONObject(Objects.requireNonNull(Helper.loadJSONFromAsset(getApplicationContext()))); // Returns a JSON string
JSONArray who = json.getJSONArray(intent);
for (int i = 0; i < who.length(); i ) {
System.out.println(who.getJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
public static String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("speech.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, StandardCharsets.UTF_8);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
我收到此錯誤:
W/System.err: org.json.JSONException: 0 型別的 java.lang.String 值 Hello 不能轉換為 JSONObject
我的代碼有什么問題?
uj5u.com熱心網友回復:
該陣列包含字串,而不是 JSONObjects。所以,
System.out.println(who.getString(i));
uj5u.com熱心網友回復:
你打電話who.getJSONObject在System.out.println(who.getJSONObject(i));。
該方法期望陣列中的該位置包含一個物件。
但是,whoJSONArray 包含字串。
所以你應該呼叫 getJsonString:https://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html#getJsonString-int-
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400894.html
