共計 694 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,你可以使用 json.org 或者 Gson 等 JSON 庫來解析和操作 JSON 數據。以下是使用 json.org 庫解析 JSON 對象的示例:
import org.json.JSONObject;
public class Main {public static void main(String[] args) {
// JSON 字符串
String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 創建 JSON 對象
JSONObject jsonObject = new JSONObject(jsonStr);
// 獲取 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);
}
}
上述代碼中,我們首先定義了一個 JSON 字符串,然后使用 JSONObject
類創建了一個 JSON 對象。接下來,我們可以使用 getString()
、getInt()
等方法從 JSON 對象中提取數據。在這個例子中,我們提取了 ”name”、”age” 和 ”city” 字段的值并打印出來。
請注意,你需要確保在代碼中引入 json.org 庫的相關依賴。
丸趣 TV 網 – 提供最優質的資源集合!
正文完