添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
* @return {@link T} private static T getJsonPathFieldValue(String dataJson, String jsonPath, TypeRef typeRef) { if (!StrUtil.startWith(jsonPath, "$.")) { // 如果不是以 $. 开头,添加 $. jsonPath = "$.".concat(jsonPath); try { Configuration jsonPathConfig = Configuration.builder() .jsonProvider(new JacksonJsonProvider()) .mappingProvider(new JacksonMappingProvider()) .build(); return JsonPath.using(jsonPathConfig).parse(dataJson).read(jsonPath, typeRef); } catch (Exception e) { log.error("JsonPath 转换数据异常,jsonPath: {}", jsonPath, e); return null;

2. 获取多层级 json 中任意对象的一个字段是什么值的另一个字段

List<String> sensitiveFieldList = getJsonPathFieldValue(mateEntity.getWebJson(), "$..[?(@.options.customProps.isSensitive == true)].model", new TypeRef<List<String>>() {});
  • $..:任意位置
  • [?()]:过滤表达式
  • @:当前对象
  • @.options.customProps.isSensitive == true:对象里面的options对象的customProps对象里面的isSensitive对象为true的对象
  • .model:对象的model字段

3. 删除对象中任意层级key字段

// 解析json
DocumentContext documentContext = JsonPath.parse(dataJson);
// 去除敏感字段数据,因为不知道敏感字段的层级,只能一个个删除
sensitiveFieldList.forEach(sensitiveField -> documentContext.delete("$..".concat(sensitiveField)));

4. 过滤任意为空的对象

例如: {}[]

$.[?(@.list.length() > 0)]

如果json是这样

"table_f2fh3xpb": [{}, {}], "subform_023cl7t5": [{ "table_y4h2ooe9": [{ "input_f": "1fff" "input_h": ""

想移除掉{}和空字符串

DocumentContext documentContext = JsonPath.parse(json);
documentContext.delete("$..[?(@.length() == 0)]");

5. 获取id值当前层级的子级数据

"data": [{ "id": 123, "children": [{ "cid": "111" "id": 456, "children": [{ "cid": "222"

id等于123或456层级子级数据怎么获取

@SneakyThrows
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "\t\"data\": [{\n" +
                "\t\t\t\"id\": 123,\n" +
                "\t\t\t\"children\": [{\n" +
                "\t\t\t\t\"cid\": \"111\"\n" +
                "\t\t\t}]\n" +
                "\t\t}, {\n" +
                "\t\t\t\"id\": 456,\n" +
                "\t\t\t\"children\": [{\n" +
                "\t\t\t\t\"cid\": \"222\"\n" +
                "\t\t\t}]\n" +
                "\t\t}\n" +
                "\n" +
                "\t]\n" +
        Object object = JsonPath.read(JSONUtil.parse(jsonStr), "$.data.*.id");
        List<Integer> list = Convert.toList(Integer.class, object);
        list.forEach(id -> {
            // 获取每个id对应的children
            Object read = JsonPath.read(JSONUtil.parse(jsonStr), "$.data[?(@.id ==" +  id + ")].children");
            log.info("children: {}", read.toString());
        log.info("read: {}", object.toString());

6. 获取多个字段值当前层级的子级数据—父级和子级不在一个层级

"data": [{ "age": 123, "name": "张三", "children": [{ "cid": "111" "age": 456, "name": "李四", "children": [{ "cid": "222"

age等于123和name等于张三 或 age等于456和name等于李四 层级子级数据怎么获取

    @SneakyThrows
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "\t\"data\": [{\n" +
                "\t\t\"age\": 123,\n" +
                "\t\t\"name\": \"张三\",\n" +
                "\t\t\"children\": [{\n" +
                "\t\t\t\"cid\": \"111\"\n" +
                "\t\t}]\n" +
                "\t}, {\n" +
                "\t\t\"age\": 456,\n" +
                "\t\t\"name\": \"李四\",\n" +
                "\t\t\"children\": [{\n" +
                "\t\t\t\"cid\": \"222\"\n" +
                "\t\t}]\n" +
                "\t}]\n" +
        DocumentContext documentContext = JsonPath.parse(jsonStr);
        Object object = documentContext.read("$.data.*");
        List<JSONObject> jsonObjects = Convert.toList(JSONObject.class, object);
        log.info("jsonObjects: {}", JSONUtil.toJsonStr(jsonObjects));
        // 唯一字段---确定数据源否存在
        Set<String> uniqueFields = ImmutableSet.of("age", "name");
        // 子级数据路径模板
        String sonPathFormat = "$.data[?(@.age == {age} && @.name == '{name}')].children";
        jsonObjects.forEach(o -> {
            // 子级数据路径
            String sonPath = StrUtil.format(sonPathFormat, new Dict().set("age", o.get("age")).set("name", o.get("name")));
            // 获取多个唯一字段对应的children
            Object read = documentContext.read(sonPath);
            log.info("children: {}", read.toString());
 

sonPathFormat$.data[?(@.age == {age} && @.name == '{name}')].children

7. 获取多个字段值当前层级的子级数据—父级和子级在一个层级

"data": [{ "age": 123, "name": "张三", "cid": "111" "age": 456, "name": "李四", "cid": "222"

age等于123和name等于张三 或 age等于456和name等于李四 层级当前层级数据怎么获取

  @SneakyThrows
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "\t\"data\": [{\n" +
                "\t\t\"age\": 123,\n" +
                "\t\t\"name\": \"张三\",\n" +
                "\t\t\"cid\": \"111\"\n" +
                "\t}, {\n" +
                "\t\t\"age\": 456,\n" +
                "\t\t\"name\": \"李四\",\n" +
                "\t\t\"cid\": \"222\"\n" +
                "\t}]\n" +
        DocumentContext documentContext = JsonPath.parse(jsonStr);
        Object object = documentContext.read("$.data.*");
        List<JSONObject> jsonObjects = Convert.toList(JSONObject.class, object);
        log.info("jsonObjects: {}", JSONUtil.toJsonStr(jsonObjects));
        // 唯一字段---确定数据源否存在
        Set<String> uniqueFields = ImmutableSet.of("age", "name");
        // 子级数据路径模板
        String sonPathFormat = "$.data[?(@.age == {age} && @.name == '{name}')].*";
        jsonObjects.forEach(o -> {
            // 子级数据路径
            String sonPath = StrUtil.format(sonPathFormat, new Dict().set("age", o.get("age")).set("name", o.get("name")));
            // 获取多个唯一字段对应的children
            Object read = documentContext.read(sonPath);
            log.info("children: {}", read.toString());
 

sonPathFormat$.data[?(@.age == {age} && @.name == '{name}')].*

JSONPath是一种用于在JSON(JavaScript Object Notation)数据中定位和提取特定元素的查询语言。它类似于XPath对XML的作用,可以帮助我们轻松地按照特定的路径表达式从复杂的JSON结构中获取所需的数据。 通过使用JSONPath,开发人员可以更有效地处理和解析JSON数据,同时减少冗余代码和手动遍历的工作量。它在Web开发、API集成、数据转换等领域具有广泛的应用。