jsonpath java使用实例
时间: 2023-08-03 17:07:08 浏览: 47
下面是一个简单的 JSON 数据:
```json
{
"name": "John",
"age": 30,
"cars": [
{ "name": "Ford", "models": [ "Fiesta", "Focus", "Mustang" ] },
{ "name": "BMW", "models": [ "320", "X3", "X5" ] },
{ "name": "Fiat", "models": [ "500", "Panda" ] }
]
}
```
我们使用 JSONPath 来获取数据:
1. 导入相关的依赖包:
```xml
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
```
2. 使用 JSONPath 获取数据:
```java
import com.jayway.jsonpath.JsonPath;
import java.util.List;
public class JsonPathExample {
public static void main(String[] args) {
String json = "{ \"name\": \"John\", \"age\": 30, \"cars\": [ { \"name\": \"Ford\", \"models\": [ \"Fiesta\", \"Focus\", \"Mustang\" ] }, { \"name\": \"BMW\", \"models\": [ \"320\", \"X3\", \"X5\" ] }, { \"name\": \"Fiat\", \"models\": [ \"500\", \"Panda\" ] } ] }";
String name = JsonPath.read(json, "$.name");
int age = JsonPath.read(json, "$.age");
List<String> models = JsonPath.read(json, "$.cars[?(@.name=='BMW')].models");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("BMW models: " + models);
}
}
```
输出结果如下:
```
Name: John
Age: 30
BMW models: [320, X3, X5]
```
以上示例演示了如何使用 JSONPath 获取 JSON 数据中的某些字段。更多 JSONPath 的语法和使用方法可以参考官方文档:[https://github.com/json-path/JsonPath](https://github.com/json-path/JsonPath)。