是的,JSONPath Java 可以處理嵌套數據。JSONPath 是一種用于查詢和操作 JSON 數據的語言,它允許你使用簡潔的表達式來訪問和操作嵌套的 JSON 對象和數組。
在 Java 中,你可以使用諸如 Jackson、Gson 或 org.json 等庫來解析 JSON 數據,然后使用 JSONPath 表達式來處理嵌套數據。以下是一個使用 org.json 庫和 JSONPath 表達式處理嵌套數據的示例:
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String jsonString = "{ \"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"hobbies\": [\"reading\", \"traveling\"], \"address\": { \"street\": \"Main St\", \"number\": 42 } }";
JSONObject jsonObject = new JSONObject(jsonString);
// 查詢嵌套對象
JSONObject address = jsonObject.getJSONObject("address");
System.out.println("Address: " + address.toString());
// 查詢嵌套數組
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
System.out.println("Hobbies: " + hobbies.toString());
// 使用 JSONPath 表達式查詢嵌套數據
String name = JsonPath.read(jsonObject, "$.name");
System.out.println("Name: " + name);
int age = JsonPath.read(jsonObject, "$.age");
System.out.println("Age: " + age);
String street = JsonPath.read(jsonObject, "$.address.street");
System.out.println("Street: " + street);
}
}
在這個示例中,我們首先將 JSON 字符串解析為一個 JSONObject 對象。然后,我們使用 getJSONObject()
和 getJSONArray()
方法來訪問嵌套的對象和數組。最后,我們使用 JSONPath 的 read()
方法來查詢嵌套數據。