import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
// 示例 JSON 字符串
String jsonString = "{ \"store\": { "
+ "\"book\": [ { \"category\": \"reference\", "
+ "\"author\": \"Nigel Rees\", "
+ "\"title\": \"Sayings of the Century\", "
+ "\"price\": 8.95 } ], "
+ "\"bicycle\": { "
+ "\"color\": \"red\", "
+ "\"price\": 19.95 } } }";
try {
// 解析 JSON 字符串为 JSON 对象
JSONObject jsonObject = (JSONObject) new JSONParser().parse(jsonString);
// 使用 JsonPath 查询 JSON 数据
// 获取所有书的作者
JSONArray authors = JsonPath.read(jsonObject, "$.store.book[*].author");
System.out.println("Authors: " + authors);
// 获取自行车的颜色
String bikeColor = JsonPath.read(jsonObject, "$.store.bicycle.color");
System.out.println("Bike Color: " + bikeColor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
net.minidev.json 和 net.minidev.jsonpath.JsonPath,这些是处理 JSON 和执行 JSONPath 查询所需的库。jsonString 是一个包含书籍和自行车信息的 JSON 字符串。JSONParser 将 JSON 字符串解析为 JSONObject。$.store.book[*].author:查询所有书籍的作者。$.store.bicycle.color:查询自行车的颜色。如果你没有安装 json-smart 和 json-path 库,可以通过 Maven 或 Gradle 添加依赖:
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.4.8</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.7.0</version>
</dependency>
implementation 'net.minidev:json-smart:2.4.8'
implementation 'com.jayway.jsonpath:json-path:2.7.0'
下一篇:java int转double
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站