Java JSONPath 是一个用于处理 JSON 数据的库,它允许你使用简洁的语法来查询和操作 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 数据,从而简化代码。