處理 Java JSON 數據中的異常情況,通常需要使用 try-catch 語句來捕獲和處理特定的異常
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\" }";
try {
// 解析 JSON 字符串
JSONObject jsonObject = new JSONObject(jsonString);
// 獲取 JSON 對象中的值
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (JSONException e) {
// 處理 JSON 解析異常
System.err.println("Error parsing JSON: " + e.getMessage());
}
}
}
public class Main {
public static void main(String[] args) {
String jsonArray = "[{\"name\":\"John\"}, {\"name\":\"Jane\"}]";
try {
// 解析 JSON 數組
JSONArray jsonArray = new JSONArray(jsonArray);
// 遍歷 JSON 數組并獲取每個 JSON 對象中的值
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("Name " + (i + 1) + ": " + name);
}
} catch (JSONException e) {
// 處理 JSON 解析異常
System.err.println("Error parsing JSON array: " + e.getMessage());
}
}
}
請注意,這些示例僅展示了如何處理 JSON 數據解析過程中可能出現的異常。在實際應用中,您可能需要處理更多其他類型的異常情況。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。