共計 1228 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 Java 中,可以使用 JSON 庫如 Jackson 或 Gson 來解析 JSON 字符串并獲取其中的數組值。
下面是使用 Jackson 庫獲取 JSON 數組對象值的示例:
首先,需要導入 Jackson 庫的依賴:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
然后,使用 ObjectMapper 類來解析 JSON 字符串并獲取數組對象的值:
String jsonString = "{\"array\": [1, 2, 3]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
// 獲取數組對象
JsonNode arrayNode = jsonNode.get("array");
// 遍歷數組并獲取每個元素的值
for (JsonNode element : arrayNode) {System.out.println(element.asInt());
}
以上示例中,我們首先創建了一個包含 JSON 數組的字符串。然后,使用 ObjectMapper 類將 JSON 字符串解析為 JsonNode 對象。接下來,我們通過調用 get 方法獲取數組對象,并使用 for 循環遍歷數組并打印每個元素的值。
使用 Gson 庫也可以實現同樣的功能。首先,需要導入 Gson 庫的依賴:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
然后,使用 JsonParser 類來解析 JSON 字符串并獲取數組對象的值:
String jsonString = "{\"array\": [1, 2, 3]}";
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(jsonString);
// 獲取數組對象
JsonArray jsonArray = jsonElement.getAsJsonObject().get("array").getAsJsonArray();
// 遍歷數組并獲取每個元素的值
for (JsonElement element : jsonArray) {System.out.println(element.getAsInt());
}
以上示例中,我們首先創建了一個包含 JSON 數組的字符串。然后,使用 JsonParser 類將 JSON 字符串解析為 JsonElement 對象。接下來,我們通過調用 getAsJsonObject 方法和 get 方法來獲取數組對象,并使用 for 循環遍歷數組并打印每個元素的值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完