SpringBoot+JaywayJsonPath实现Json数据的DSL(按照指定节点表达式解析json获取指定数据)

场景

若依前后端分离版手把手教你本地搭建环境并运行项目:

若依前后端分离版手把手教你本地搭建环境并运行项目_前后端分离项目本地运行-CSDN博客

在上面搭建SpringBoot项目的基础上,并且在项目中引入fastjson、hutool等所需依赖后。

Jayway JsonPath:

GitHub - json-path/JsonPath: Java JsonPath implementation

A Java DSL for reading JSON documents

需要对接第三方接口,接口返回的json数据需要解析获取数据。

可以通过配置每个返回字段的对应json数据的表达式,使其在代码中根据配置的表达式动态获取。

注:

博客:
霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客

实现

1、添加项目依赖

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

2、JsonPath表达式引用JSON结构的方式与XPath表达式与XML文档结合使用的方式相同。

采用接口模拟工具模拟官方提供的示例json数据

{
    "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
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

3、快速开始

解析上面json数据中所有book节点的author字段信息

List<String> authors = JsonPath.read(body, "$.store.book[*].author");

获取第一本书的title字段

String title = JsonPath.read(body, "$['store']['book'][0]['title']");

也可以这样写

String title2 = JsonPath.read(body, "$.store.book[0].title");

获取所有book的数量

Integer number = JsonPath.read(body, "$..book.length()");

获取所有价格大于10的book

List<Map<String, Object>> expensiveBooks= JsonPath.read(body, "$.store.book[?(@.price > 10)]");

4、Json Path的语法较多,各种符号、函数、过滤等可参考官方文档。

下面记录一个读取json数据中指定结构的list数据。

首先需要读取所有book的数量,然后遍历循环,再通过配置的json数据的映射关系

获取配置的映射关系的表达式,进而解析获取对应字段的数据。

            int dataSize = JsonPath.read(body, "$..book.length()");
            JSONObject mapping = JSON.parseObject("{\"title\":\"$.store.book[%d].title\",\"author\":\"$.store.book[%d].author\"}");
            for (int i = 0; i < dataSize; i++) {
                String titleName = mapping.containsKey("title") ? JsonPath.read(body, String.format(mapping.getString("title"), i)).toString() : null;
                System.out.println(titleName);
                String author = mapping.containsKey("author") ? JsonPath.read(body, String.format(mapping.getString("author"), i)).toString() : null;
                System.out.println(author);
            }

其中JSON.parseObject是引用的fastjson。

单元测试结果

5、完整单元测试示例代码

​
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JsonPathTest {

    @Test
    public void getData() {
        String body = "";
        try {
            //模拟获取接口数据
            body = HttpRequest
                    .get("http://127.0.0.1:4523/m1/2858210-0-default/testJsonPath")
                    .timeout(20000)
                    .execute()
                    .body();
            //获取book的所有auther
            List<String> authors = JsonPath.read(body, "$.store.book[*].author");
            System.out.println(authors);
            //第一本book的title
            String title = JsonPath.read(body, "$['store']['book'][0]['title']");
            String title2 = JsonPath.read(body, "$.store.book[0].title");
            System.out.println(title);
            System.out.println(title2);
            //所有book 的数量
            Integer number = JsonPath.read(body, "$..book.length()");
            System.out.println(number);
            //获取所有价格大于10的book
            List<Map<String, Object>> expensiveBooks= JsonPath.read(body, "$.store.book[?(@.price > 10)]");
            System.out.println(expensiveBooks);

            //根据配置的json数据的映射关系,获取指定表达式下的数据
            int dataSize = JsonPath.read(body, "$..book.length()");
            JSONObject mapping = JSON.parseObject("{\"title\":\"$.store.book[%d].title\",\"author\":\"$.store.book[%d].author\"}");
            for (int i = 0; i < dataSize; i++) {
                String titleName = mapping.containsKey("title") ? JsonPath.read(body, String.format(mapping.getString("title"), i)).toString() : null;
                System.out.println(titleName);
                String author = mapping.containsKey("author") ? JsonPath.read(body, String.format(mapping.getString("author"), i)).toString() : null;
                System.out.println(author);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

​

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Elasticsearch 简介 ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。elasticSearch 的使用场景 1、在海量数据前提下,对数据进行检索。比如:京东,淘宝等电商项目课程目标: 1. 了解企业级搜索引擎2. 安装elasticsearch 课程目录: 01 课程介绍02 elasticsearch 简介03 elasticsearch 使用场景04 安装elasticsearch 之前先安装jdk05 安装elasticsearch06 测试elasticsearch是否安装成功 07 安装kibana08 elasticsearch 基本认识 以及添加索引和删除索引09 elasticsearch 添加查询数据10 elasticsearch 修改删除数据11 elasticsearch 有条件的查询12 分词子属性fuzzy查询13 elasticsearch 过滤使用14 elasticsearch 排序与分页15 elasticsearch 如何查询指定的字段16 elasticsearch 高亮显示17 elasticsearch 聚合18 elasticsearch mapping 概念19 elasticsearch 的中文词库20 elasticsearch 中文词库安装测试21 elasticsearch 中文词库的使用案例22 elasticsearch 自定义词库配置23 安装nginx 配置中文词库24 测试elasticsearch 自定义中文词库25 搭建项目父工程26 搭建项目bean-interface-common27 搭建search 的service web 项目28 测试项目是否能与elasticsearch联通29 创建数据库并搭建首页30 数据上传功能的实现类完成31 数据上传控制器完成32 dubbo 介绍以及安装zookeeper33 将数据从mysql 上传到elasticsearch 中34 elasticsearch查询功能分析35 编写业务需求的dsl 语句36 编写输入参数返回结果集的实体类37 实现类编写38 编写实现类中dsl 语句39 返回集结果转换40 结果测试41 测试通过输入查询条件并将数据显示到页面
您好!对于使用Spring Boot和PostgreSQL存储和操作JSON格式数据的问题,您可以按照以下步骤进行操作: 1. 首先,在您的Spring Boot项目中添加PostgreSQL的依赖。您可以在Maven或Gradle配置文件中添加以下依赖项: ```xml <!-- Maven --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>版本号</version> </dependency> ``` ```groovy // Gradle implementation 'org.postgresql:postgresql:版本号' ``` 2. 确保您已经在PostgreSQL数据库中创建了一个表,该表包含一个JSON类型的列用于存储JSON数据。您可以使用以下DDL语句创建一个表: ```sql CREATE TABLE your_table ( id SERIAL PRIMARY KEY, json_data JSON ); ``` 3. 在您的Spring Boot应用程序中,您可以使用JPA(Java Persistence API)或Spring Data JDBC来访问和操作数据库。 - 如果您选择使用JPA,您需要创建一个实体类来映射到数据库表。在实体类中,您可以使用`@Column(columnDefinition = "json")`注解来指定该字段应该使用JSON数据类型。例如: ```java @Entity @Table(name = "your_table") public class YourEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(columnDefinition = "json") private String jsonData; // Getters and setters } ``` - 如果您选择使用Spring Data JDBC,您可以创建一个简单的POJO类,其中包含一个与数据库表列对应的字段。例如: ```java public class YourEntity { private Long id; private String jsonData; // Getters and setters } ``` 4. 在您的应用程序中,您可以使用JPA的Repository接口或Spring Data JDBC的Repository接口来执行数据库操作。例如,使用JPA的Repository接口: ```java public interface YourRepository extends JpaRepository<YourEntity, Long> { } ``` 5. 现在,您可以在您的业务逻辑中使用Repository接口来存储和检索JSON数据。例如,使用JPA的Repository接口: ```java @Service public class YourService { private final YourRepository yourRepository; public YourService(YourRepository yourRepository) { this.yourRepository = yourRepository; } public void saveJsonData(String jsonData) { YourEntity entity = new YourEntity(); entity.setJsonData(jsonData); yourRepository.save(entity); } public List<YourEntity> getAllEntities() { return yourRepository.findAll(); } } ``` 这样,您就可以使用Spring Boot和PostgreSQL来存储和操作JSON格式数据了。希望对您有所帮助!如有任何疑问,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值