Java JSONPath 是一個用于處理 JSON 數(shù)據(jù)的庫,它允許你使用簡潔的語法來查詢和操作 JSON 對象。以下是一些簡化代碼的示例:
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
DocumentContext documentContext = JsonPath.parse(json);
String name = documentContext.read("$.name");
System.out.println("Name: " + name);
}
}
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
DocumentContext documentContext = JsonPath.parse(json);
String name = documentContext.read("$.name");
int age = documentContext.read("$.age");
String city = documentContext.read("$.city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
}
}
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String json = "[{\"name\":\"John\"}, {\"name\":\"Jane\"}, {\"name\":\"Doe\"}]";
DocumentContext documentContext = JsonPath.parse(json);
String firstPersonName = documentContext.read("[0].name");
String secondPersonName = documentContext.read("[1].name");
String thirdPersonName = documentContext.read("[2].name");
System.out.println("First person name: " + firstPersonName);
System.out.println("Second person name: " + secondPersonName);
System.out.println("Third person name: " + thirdPersonName);
}
}
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;
import com.jayway.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String json = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Jane\", \"age\":28}, {\"name\":\"Doe\", \"age\":35}]";
DocumentContext documentContext = JsonPath.parse(json);
String[] names = documentContext.read("$.[?(@.age < 30)]", String[].class);
System.out.println("Names of people with age less than 30: " + names[0] + ", " + names[1]);
}
}
通過使用 JSONPath 的簡潔語法,你可以更輕松地查詢和操作 JSON 數(shù)據(jù),從而簡化代碼。