Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java jsonpath

作者:余烬已熄   发布日期:2025-10-30   浏览:92

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();
        }
    }
}

解释说明:

  1. 导入依赖:代码中使用了 net.minidev.jsonnet.minidev.jsonpath.JsonPath,这些是处理 JSON 和执行 JSONPath 查询所需的库。
  2. 示例 JSON 字符串jsonString 是一个包含书籍和自行车信息的 JSON 字符串。
  3. 解析 JSON:使用 JSONParser 将 JSON 字符串解析为 JSONObject
  4. JsonPath 查询
    • $.store.book[*].author:查询所有书籍的作者。
    • $.store.bicycle.color:查询自行车的颜色。
  5. 输出结果:将查询到的结果打印出来。

如果你没有安装 json-smartjson-path 库,可以通过 Maven 或 Gradle 添加依赖:

Maven:

<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>

Gradle:

implementation 'net.minidev:json-smart:2.4.8'
implementation 'com.jayway.jsonpath:json-path:2.7.0'

上一篇:java map转jsonobject

下一篇:java int转double

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站