java怎么取jsonobject里面數(shù)據(jù)

小億
147
2023-08-24 23:58:59
欄目: 編程語言

在Java中,你可以使用json.org或者Gson等JSON庫來解析和操作JSON數(shù)據(jù)。以下是使用json.org庫解析JSON對(duì)象的示例:

import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// JSON字符串
String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 創(chuàng)建JSON對(duì)象
JSONObject jsonObject = new JSONObject(jsonStr);
// 獲取JSON對(duì)象中的數(shù)據(jù)
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
// 打印數(shù)據(jù)
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
}
}

上述代碼中,我們首先定義了一個(gè)JSON字符串,然后使用JSONObject類創(chuàng)建了一個(gè)JSON對(duì)象。接下來,我們可以使用getString()、getInt()等方法從JSON對(duì)象中提取數(shù)據(jù)。在這個(gè)例子中,我們提取了"name"、"age"和"city"字段的值并打印出來。

請(qǐng)注意,你需要確保在代碼中引入json.org庫的相關(guān)依賴。

0