• 解析多层级 JSON 如:get(A.B.C)


    最近有一个需求,需要用定时任务调用第三方接口,第三方接口前面可能有多层,即第三层传递的参数来自第二层接口返回的结果,参数需要在前台配置,参数是灵活配置的,如:第二层需要第一层返回结果的 token,需要通过 A.B.C 去解析 JSON 获取 token

    比如如下 JSON,前端传递位置就能获取具体的值

    • result.teacher[0].subject[2].name,
    • result.teacher[0].subject[0].score[1][1][0],
    • result.teacher[0].subject[2].score[1][1].name,
    • timestamp[1]
    {
        "result": {
            "teacher": [
                {
                    "name": "admin",
                    "subject": [
                        {
                            "name": "语文",
                            "score": [
                                [
                                    [1, 2],
                                    [3,4]
                                ],
                                [
                                    [5,6],
                                    [7,8]
                                ]
                            ]
                        },
                        {
                            "name": "数学",
                            "score": 99
                        },
                        {
                            "name": "英语",
                            "score": [
                                [
                                    {
                                        "name": "初一期中",
                                        "score": 66
                                    },
                                    {
                                        "name": "初一期末",
                                        "score": 77
                                    }
                                ],
                                [
                                    {
                                        "name": "初二期中",
                                        "score": 88
                                    },
                                    {
                                        "name": "初二期末",
                                        "score": 99
                                    }
                                ]
                            ]
                        }
                    ],
                    "age": 99,
                    "address": "西安市"
                }
            ]
        },
        "timestamp": [123, 456,789]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    直接上代码,代码比较简单,目前暂时满足需求,后续有修改再追加

    public class Test {
        public static void main(String[] args) {
            String s = "{\n" +
                    "    'result': {\n" +
                    "        'teacher': [\n" +
                    "            {\n" +
                    "                'name': 'admin',\n" +
                    "                'subject': [\n" +
                    "                    {'name': '语文','score': [[[1,2],[3,4]],[[5,6],[7,8]]]},\n" +
                    "                    {'name': '数学','score': 99},\n" +
                    "                    {'name': '英语', 'score': [[{'name':'初一期中', 'score':66},{'name':'初一期末', 'score':77}],[{'name':'初二期中', 'score':88},{'name':'初二期末', 'score':99}]]}\n" +
                    "                ],\n" +
                    "                'age': 99,\n" +
                    "                'address': '西安市'\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    },\n" +
                    "    'timestamp': [123, 456,789]\n" +
                    "}";
            JSONObject jsonObject = JSONObject.parseObject(s);
            String lockValue = "result.teacher[0].subject[2].name";
            String lockValue2 = "result.teacher[0].subject[0].score[1][1][0]";
            String lockValue3 = "result.teacher[0].subject[2].score[1][1].name";
            String lockValue4 = "timestamp[1]";
            System.out.println(resolveJson(lockValue, jsonObject));
            System.out.println(resolveJson(lockValue2, jsonObject));
            System.out.println(resolveJson(lockValue3, jsonObject));
            System.out.println(resolveJson(lockValue4, jsonObject));
        }
    
        /**
         * 解析 json ,支持 A.B.C,A[0].B.[2]
         */
        public static String resolveJson(String lockValue, JSONObject jsonObject) {
            String[] split = lockValue.split("\\.");
            Object obj = null;
            for (int i = 0; i < split.length; i++) {
                try {
                    // 判断是否解析数组
                    if (split[i].contains("[") && split[i].contains("]")) {
                        String prefix = split[i].substring(0, split[i].indexOf("["));
                        // 判断是否解析多维数组
                        if (split[i].contains("][")) {
                            obj = resolveManyArr(jsonObject, split[i]);
                        } else {
                            obj = jsonObject.get(prefix);
                            String index = split[i].substring(prefix.length() + 1, split[i].indexOf("]"));
                            obj = JSONArray.parseArray(JSONObject.toJSONString(obj)).get(Integer.parseInt(index));
                        }
                    } else {
                        obj = jsonObject.get(split[i]);
                    }
                    if (i != split.length - 1) {
                        jsonObject = JSONObject.parseObject(JSONObject.toJSONString(obj));
                    }
                } catch (Exception e) {
                	// 解析错误处理
                    JSONObject errorJson = new JSONObject();
                    errorJson.put("param", split[i]);
                    errorJson.put("value", obj);
                    errorJson.put("error", e.getMessage());
                    obj = JSONObject.toJSONString(errorJson);
                    System.out.println("参数解析失败-----" + split[i]);
                    e.printStackTrace();
                }
            }
    
            String paramValue;
            try {
                paramValue = JSONObject.toJSONString(obj);
            } catch (Exception e) {
                assert jsonObject != null;
                paramValue = jsonObject.toString();
            }
            return paramValue;
        }
    
        /**
         * Description: 解析多维数组
         *
         * @return: java.lang.Object
         */
    
        public static Object resolveManyArr(JSONObject jsonObject, String resolveParam) {
            JSONArray jsonArray = null;
            Object obj = null;
            String prefix = resolveParam.substring(0, resolveParam.indexOf("["));
            if (resolveParam.contains("][")) {
                String[] indArr = resolveParam.substring(prefix.length() + 1, resolveParam.length() - 1).split("]\\[");
                if (indArr.length > 1) {
                    for (int j = 0; j < indArr.length; j++) {
                        obj = j == 0 ? jsonObject.getJSONArray(prefix).get(Integer.parseInt(indArr[j])) : JSONArray.parseArray(JSONObject.toJSONString(jsonArray)).get(Integer.parseInt(indArr[j]));
                        if (j != indArr.length - 1) {
                            jsonArray = JSONArray.parseArray(JSONObject.toJSONString(obj));
                        }
                    }
                }
            }
            return obj;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101

    测试结果
    在这里插入图片描述

  • 相关阅读:
    学习偏态分布的相关知识和原理的4篇论文推荐
    Java设计模式之原型模式
    一文详解TCP三次握手的状态迁移(从应用层到内核传输层)
    2023年陕西省安全员B证证考试题库及陕西省安全员B证试题解析
    章十九、JavaVUE —— 框架、指令、声明周期、Vue-cli、组件路由、Element
    Laravel 模型的关联写入&多对多的关联写入 ⑩③
    h5页面生成分享海报(保存图片、分享)
    麒麟系统+lnmp+laravel 搭建
    根据机械臂视频模拟出运动路线
    达梦:dmfldr 数据装载
  • 原文地址:https://blog.csdn.net/qq_41538097/article/details/127852825