当前位置: 首页 > article >正文

JsonPath 更便捷的JSON解析工具

需求:
可读性更好的 Json 字符串解析。

JsonPath

JsonPath 是一个用于解析和查询 JSON 数据的工具,类似于 XPath 用于 XML。使用 JsonPath,可以轻松提取 JSON 中的特定数据。
适合的场景:

  • 从json字符串获取变量值

优点:

  • 减少不必要的实体类或者 Map
  • 减少不必要的解析代码,例如 objectMapper

添加依赖:

<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <version>2.6.0</version>
</dependency>

2.1 举个例子

优化前的代码:

 class AttendanceItem {
   String absType;
   String absNum;

   // Getters and setters
   public String getAbsType() { return absType; }
   public void setAbsType(String absType) { this.absType = absType; }
   public String getAbsNum() { return absNum; }
   public void setAbsNum(String absNum) { this.absNum = absNum; }
}

class AttendanceList {
   List<AttendanceItem> attendanceList;

   // Getter
   public List<AttendanceItem> getAttendanceList() { return attendanceList; }
}

public static get() {
   String jsonString = "{\"attendanceList\":[{\"absType\":\"LV48\",\"absNum\":\"5\"},{\"absType\":\"LV48\",\"absNum\":\"6\"}]}";
   Gson gson = new Gson();
   AttendanceList attendanceList = gson.fromJson(jsonString, AttendanceList.class);
   List<AttendanceItem> items = attendanceList.getAttendanceList();
   if (items != null && !items.isEmpty()) {
       for (AttendanceItem item : items) {
           if ("LV48".equals(item.getAbsType())) {
               System.out.println("absNum: " + item.getAbsNum());
           }
       }
   } else {
       System.out.println("No matching absType found");
   }
}

优化后的代码:

 public static void better() {
    String jsonString = "{\"attendanceList\":[{\"absType\":\"LV48\",\"absNum\":\"5\"},{\"absType\":\"LV48\",\"absNum\":\"6\"}]}";
    // 通过表达式获取旷工(absType=48)的天数(absNum)
    String jsonPathExpression = "$.attendanceList[?(@.absType == 'LV48')].absNum";
    // Parse the JSON string and extract the list of matching absNum values
    List<String> absNumList = JsonPath.read(jsonString, jsonPathExpression);
    if (!absNumList.isEmpty()) {
        for (String absNum : absNumList) {
            System.out.println("absNum: " + absNum);
        }
    } else {
        System.out.println("No matching absType found");
    }
}

2.2 JsonPath 基础

JsonPath 对大小写敏感,确保在查询时正确使用。

举个例子:

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}
  • 获取所有书籍的标题: $.store.book[*].title
  • 获取价格大于 10 的书籍: $.store.book[?(@.price > 10)].title
  • 获取所有书籍的作者和价格: $.store.book[*][‘author’, ‘price’]

2.2.1 基础语法

  • 根节点: $
    • 表示 JSON 数据的根。
  • 子节点: . 或 []
    • . 用于访问子节点。
    • [] 用于访问数组元素。

2.2.2 路径表达式

  • 访问单个属性: $.store.book
    • 获取 store 对象下的 book 数组。
  • 访问数组元素: $.store.book[0]
    • 获取 book 数组中的第一本书。
  • 获取多个元素: $.store.book[0, 1]
    • 获取 book 数组中的第一本和第二本书。

2.2.3. 通配符

  • 通配符 *:
    • $.store.book[*] 获取 book 数组中的所有书籍。
    • $.store.* 获取 store 下的所有属性。

2.2.4 过滤器

  • 条件过滤: $.store.book[?(@.price < 10)]
    • 获取所有价格低于 10 的书籍。
  • 多条件过滤: $.store.book[?(@.category == ‘fiction’ && @.price < 20)]
    • 获取类别为 fiction 且价格低于 20 的书籍。

2.2.5 获取属性值

  • 选择多个属性: $.store.book[*][‘title’, ‘author’]
    • 获取所有书籍的标题和作者。

2.2.6 数组操作

  • 数组切片: $.store.book[0:2]
    • 获取 book 数组中的前两本书(索引 0 和 1)。
  • 数组长度: $.store.book.length()
    • 获取 book 数组的长度。

2.2.7 复杂查询

  • 获取嵌套对象属性: $.store.bicycle.color
    • 获取 bicycle 对象的颜色属性。
  • 获取所有书籍的价格总和: $.store.book[*].price.sum()
    • 计算所有书籍价格的总和(需要支持的 JsonPath 库)。

http://www.kler.cn/a/368922.html

相关文章:

  • jvm虚拟机介绍
  • VAE中的“变分”什么
  • RabbitMQ 确认模式(Acknowledgements Mode)详解
  • ReactOS系统中平衡二叉树。给定地址超导其所属区块MmFindRegion()
  • 【Qt 读取、修改、存储.ini文件】及完整示例
  • vue3+vite 部署npm 包
  • Vue2自定义指令及插槽
  • AI 提示词(Prompt)入门 :ChatGPT 4.0 高级功能指南
  • 「C/C++」C++ STL容器库 之 std::list 双向链表容器
  • 不用梅森公式看流程图写式子 和看式子画流程图
  • JavaSE:16、Java IO
  • XJ05、消费金融|额度生命周期管理及额度产品设计
  • glibc中xdr的一个bug
  • python kafka 发送/接收 消息
  • 协议 HTTP
  • WPF+MVVM案例实战(八)- 自定义开关控件封装实现
  • Docker 常用命令全解析:提升对雷池社区版的使用经验
  • 我在1024谈华为
  • SLAM是什么,分类
  • MySQL基础快速复习及高级语法学习
  • Maven入门到进阶:构建、依赖与插件管理详解
  • 在项目中如何实现 Redis 分布式锁?
  • Golang | Leetcode Golang题解之第506题相对名次
  • 【React系列五】—React学习历程的分享
  • C# OOP面试题精选 面向新手/SOLID原则/设计模式++ 长期更新
  • 为什么在网络中不能直接传输数据