共計 1024 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中解析多層嵌套的 JSON 數據可以使用一些流行的 JSON 解析庫,例如 Jackson、Gson 或者 org.json。以下是使用 Jackson 庫解析多層嵌套的 JSON 數據的示例代碼:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParser {public static void main(String[] args) {String json = "{\"name\": \"John\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"New York\"}}";
try {ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
JsonNode addressNode = jsonNode.get("address");
String street = addressNode.get("street").asText();
String city = addressNode.get("city").asText();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Street: " + street);
System.out.println("City: " + city);
} catch (Exception e) {e.printStackTrace();
}
}
}
在上面的示例中,我們使用 Jackson 庫的 ObjectMapper 類來解析 JSON 數據,并使用 JsonNode 對象獲取多層嵌套的數據。通過調用 get 方法并傳入相應的鍵值,我們可以獲取到 JSON 數據中的具體值。
使用其他 JSON 解析庫也類似,只是具體的 API 可能會有所不同。您可以根據自己的喜好和項目需求選擇適合的 JSON 解析庫來解析多層嵌套的 JSON 數據。
丸趣 TV 網 – 提供最優質的資源集合!
正文完