共計 975 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Java 中解析 JSON 數(shù)組通常使用第三方庫如 Gson 或 Jackson。下面是使用 Gson 庫解析 JSON 數(shù)組的示例代碼:
- 首先,確保你已經(jīng)引入了 Gson 庫,如果沒有可以在 pom.xml 文件中添加以下依賴:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.7</version>
</dependency>
- 創(chuàng)建一個 JSON 數(shù)組的示例數(shù)據(jù):
String json = "[{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 30}]";
- 使用 Gson 庫解析 JSON 數(shù)組:
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class JsonArrayExample {public static void main(String[] args) {String json = "[{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 30}]";
Gson gson = new Gson();
JsonArray jsonArray = JsonParser.parseString(json).getAsJsonArray();
for (JsonElement element : jsonArray) {String name = element.getAsJsonObject().get("name").getAsString();
int age = element.getAsJsonObject().get("age").getAsInt();
System.out.println("Name: " + name + ", Age: " + age);
}
}
}
上面的代碼將會解析 JSON 數(shù)組并輸出每個元素的 "name" 和 "age" 字段的值。請確保你已經(jīng)了解所使用的 JSON 數(shù)據(jù)結(jié)構(gòu)以及元素的類型,以便正確解析 JSON 數(shù)組。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完