JSONUtil,兼容fast-json路径过深或错误报错的问题



import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JSONUtil {

    /**
     * 获取[]中间的字符
     */
    public static Pattern pattern = Pattern.compile("\\[(.*?)]");

    /**
     * 获取json深度结构里面的值,如果值不存在或者路径错误,不会报错,会直接返回空
     * @param jsonObject json
     * @param expression json获取路径的表达式  样例:"{lll}.{mmm}.{jjjj}.[444]0.a",{}代表json对象,[]代表json数组,[]后面的数字代表取第几个数组中的元素,什么都不加代表取的属性的值
     * @return
     */
    public static String getString(JSONObject jsonObject, String expression) {
        if (jsonObject == null) {
            return null;
        }
        if(StrUtil.isEmpty(expression)){
            return null;
        }
        JSONObject temp=jsonObject;
        String[] array = expression.split("\\.");
        for (int i = 0; i < array.length; i++) {
            String s = array[i];
            if (i == (array.length - 1)) {
                return temp.getString(s);
            }
            if (s.startsWith("{") && s.endsWith("}")) {
                temp = temp.getJSONObject(removeTextAndLastBracket(s));
                if(temp==null){
                    return null;
                }
            }
            if (s.startsWith("[") && s.contains("]")) {
                String key = getParamInArray(s);
                if(s.split("]").length<2){
                    return null;
                }
                int index = Integer.parseInt(s.split("]")[1]);
                if(temp.getJSONArray(key)==null){
                    return null;
                }
                if(index>=temp.getJSONArray(key).size()){
                    return null;
                }
                temp = temp.getJSONArray(key).getJSONObject(index);
                if(temp==null){
                    return null;
                }
            }
        }
        return null;
    }

    public static <T> T get(JSONObject jsonObject, String expression,Class<T> clazz){
        String o=getString(jsonObject, expression);
        if(StrUtil.isEmpty(o)){
            return null;
        }
        return Convert.convert(clazz, o);
    }



    public static JSONObject getJSONObject(JSONObject jsonObject, String expression) {
        if (jsonObject == null) {
            return null;
        }
        if(StrUtil.isEmpty(expression)){
            return null;
        }
        JSONObject temp=jsonObject;
        String[] array = expression.split("\\.");
        for (int i = 0; i < array.length; i++) {
            String s = array[i];
            if (i == (array.length - 1)) {
                if(s.startsWith("{") && s.endsWith("}")){
                    return temp.getJSONObject(removeTextAndLastBracket(s));
                }
                if(s.startsWith("[") && s.contains("]")){
                    String key = getParamInArray(s);
                    if(s.split("]").length<2){
                        return null;
                    }
                    int index = Integer.parseInt(s.split("]")[1]);
                    if(temp.getJSONArray(key)==null){
                        return null;
                    }
                    if(index>=temp.getJSONArray(key).size()){
                        return null;
                    }
                    temp = temp.getJSONArray(key).getJSONObject(index);
                    return temp;
                }

            }
            if (s.startsWith("{") && s.endsWith("}")) {
                temp = temp.getJSONObject(removeTextAndLastBracket(s));
                if(temp==null){
                    return null;
                }
            }
            if (s.startsWith("[") && s.contains("]")) {
                String key = getParamInArray(s);
                int index = Integer.parseInt(s.split("]")[1]);
                if(temp.getJSONArray(key)==null){
                    return null;
                }
                if(index>=temp.getJSONArray(key).size()){
                    return null;
                }
                temp = temp.getJSONArray(key).getJSONObject(index);
                if(temp==null){
                    return null;
                }
            }
        }
        return null;
    }

    public static JSONArray getJSONArray(JSONObject jsonObject, String expression){
        if (jsonObject == null) {
            return null;
        }
        if(StrUtil.isEmpty(expression)){
            return null;
        }
        JSONObject temp=jsonObject;
        String[] array = expression.split("\\.");
        for (int i = 0; i < array.length; i++) {
            String s = array[i];
            if (i == (array.length - 1)) {

                try {
                    return temp.getJSONArray(removeTextAndLastBracket(s));
                } catch (Exception e) {
                    return null;
                }
            }
            if (s.startsWith("{") && s.endsWith("}")) {
                temp = temp.getJSONObject(removeTextAndLastBracket(s));
                if(temp==null){
                    return null;
                }
            }
            if (s.startsWith("[") && s.contains("]")) {
                String key = getParamInArray(s);
                if(s.split("]").length<2){
                    return null;
                }
                int index = Integer.parseInt(s.split("]")[1]);
                if(temp.getJSONArray(key)==null){
                    return null;
                }
                if(index>=temp.getJSONArray(key).size()){
                    return null;
                }
                temp = temp.getJSONArray(key).getJSONObject(index);
                if(temp==null){
                    return null;
                }
            }
        }
        return null;
    }


    private static String removeTextAndLastBracket(String string) {
        if (StrUtil.isEmpty(string)) {
            return string;
        }
        StringBuilder str = new StringBuilder(string);
        int i = 0;
        do {
            str.deleteCharAt(i);
            i++;
        } while (string.equals("("));
        str.deleteCharAt(string.length() - 2);
        return str.toString();
    }

    private static String getParamInArray(String s) {
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static void main(String[] args) {
        String json="{\n" +
                "    \"lll\": {\n" +
                "        \"mmm\": {\n" +
                "            \"jjjj\": {\n" +
                "                \"444\": [\n" +
                "                    {\n" +
                "                        \"a\":23.24\n" +
                "                    }\n" +
                "                ]\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}";
        JSONObject jsonObject= JSON.parseObject(json);
        System.out.println(JSONUtil.get(jsonObject,"{lll}.{mmm}.{jjjj}.[444]0.a", Boolean.class));
        System.out.println(JSONUtil.getString(jsonObject,"lll"));
        System.out.println(JSONUtil.getJSONObject(jsonObject,"{lll}.{mmm}.{jjjj}.[444]0"));
        System.out.println(JSONUtil.getJSONArray(jsonObject,"{lll}.{mmm}.{jjjj}.[444]"));


    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值