基于正则实现json解析

正则实现简单json解析

  • 使用简单正则搜索匹配
  • 弱匹配,可以匹配json格式,但是不会识别json语法
  • 支持多行注释/**/和单行注释//
  • 键:使用双引号,值:使用双引号,
  • float:会识别定义一个.之后的.不是识别,例如:15.1626.12210,解释:15.1626
package com.demo.myapplication;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 使用简单正则搜索匹配
// 弱匹配,可以匹配json格式,但是不会识别json语法
// 支持多行注释/**/和单行注释//
// 键:使用双引号,值:使用双引号,
// float:会识别定义一个.之后的.不是识别,例如:15.1626.12210,解释:15.1626


// json 格式示例
//{ 
//	"StringArray": ["1","fdasfasdfs","发大水发多少覆盖"], 
//	"IntArray":[100,5,6,9,8,7,3,6,4,2],
//	"BoolAray":[true,true,false,true,true,true],
//	"FloatArray":[0.1,0.2,0.6,0.6,0.8,0.8,10.65],
//	
//	"Float":12656.501,
//	"Bool": true,
//	"String":"小强",
//    "Int": 11,
//	"obj":
//	{
//		"StringArray": ["Shenzhen", "Beijing", "Nanjing", "Guangzhou"], 
//		"IntArray":[1,5,6,9,8,7,3,6,4,2],
//		"BoolAray":[false,true,false,true,true,true],
//		"FloatArray":[9.1],
//		"obj":
//		{
//			"StringArray": ["Shenzhen", "Beijing", "Nanjing", "Guangzhou"], 
//			"IntArray":[1,5,6,9,8,7,3,6,4,2],
//			"BoolAray":[false,true,false,true,true,true],
//			"FloatArray":[0.3,0.8,45.9,0.65,53.9],
//			"Float":10.501,
//			"String":"小美",
//			"Int": 990,
//			"Bool": false
//		},
//		"Float":5656.561212,
//		"String":"小明",
//		"Int": 19,
//		"Bool": true
//	},
//	"objs":
//	[
//		{"name":"小白虫","age":18,"married":false},
//		{"name":"小黑虫","age":20,"married":false},
//		{"name":"号地块","age":25,"married":true},
//		{"name":"来接你","age":10,"married":true},
//		{"name":"美女呢","age":21,"married":false},
//		{"name":"送给你","age":26,"married":true}
//	]
//} 
public class JsonUtil {
    //region 单例
    private static String jsonStr;

    private JsonUtil() {
    }

    private static JsonUtil instance;

    public static JsonUtil getInstance(String jsonStr) {
        if (instance == null) {
            instance = new JsonUtil();
        }
        JsonUtil.jsonStr = jsonStr;
        Reduce();
        return instance;
    }

    private static void Reduce() //json 压缩
    {
        String patternStr = "";
        Pattern pattern = null;
        Matcher matcher = null;
        //region ******************* 移除多行注释 ***************************
        // /\*[\s\S]*?\*/
        // 移除多行注释
        patternStr = "/\\*[\\s\\S]*?\\*/";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            jsonStr = matcher.replaceAll("");
        }
        //endregion
        //region ******************* 移除单行注释 ***************************
        // //[\s\S]*?\n
        // 移除单行注释
        patternStr = "//[\\s\\S]*?\\n";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            jsonStr = matcher.replaceAll("");
        }
        //endregion
        //region ******************* 移除空白字符 ***************************
        // Json 压缩

        // "[\s\S]*?"
        // 匹配引号及其内容
        // \s
        // 匹配空白字符
        int start = 0;
        int end = 0;
        StringBuffer sb = new StringBuffer();
        List<Integer> starts = new ArrayList<>();
        List<Integer> ends = new ArrayList<>();
        patternStr = "\"[\\s\\S]*?\"";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            end = matcher.start();
            starts.add(start);
            ends.add(end);
            start = matcher.end();
        }
        end = jsonStr.length();
        starts.add(start);
        ends.add(end);
        //
        patternStr = "\\s";
        pattern = Pattern.compile(patternStr);
        for (int i = starts.size() - 1; i >= 0; i--) {
            matcher = pattern.matcher(jsonStr);
            matcher.region(starts.get(i), ends.get(i));
            sb.delete(0, sb.length());//清空缓存
            while (matcher.find()) {
                matcher.appendReplacement(sb, "");
            }
            matcher.appendTail(sb);
            jsonStr = sb.toString() + jsonStr.substring(ends.get(i), jsonStr.length());
        }
        //endregion
    }

    //endregion
    //region get
    public boolean getBool(String key) throws Exception {
        // (?<=Bool":\s{0,10})(true|false)\b
        // "Bool": false,
        // 匹配上面的 false
        String patternStr = "(?<=" + key + "\":\\s{0,10})(true|false)\\b";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                return Boolean.parseBoolean(matcher.group());
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public int getInt(String key) throws Exception {
        // (?<=Int":\s{0,10})[0-9]+
        // "Int":11,
        // 匹配上面的 11
        String patternStr = "(?<=" + key + "\":\\s{0,10})[0-9]+";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                return Integer.parseInt(matcher.group());
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String getString(String key) throws Exception {
        // (?<=String":\s{0,10}\")[\w\W]*?(?=\")
        // "String":"小强",
        // 匹配上面的 小强
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\\")[\\w\\W]*?(?=\\\")";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                return matcher.group();
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public float getFolat(String key) throws Exception {
        // (?<=Float":\s{0,10})\d+(\.\d*)?
        // "Float":"12656.501",
        // 匹配上面的 12656.501
        String patternStr = "(?<=" + key + "\":\\s{0,10})\\d+(\\.\\d*)?";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                return Float.parseFloat(matcher.group());
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String getJsonObj(String key) throws Exception {
        int posStart = 0;
        int posEnd = 0;
        String patternStr = "\"" + key + "\":";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                posStart = matcher.end();
                pattern = Pattern.compile("\\}");
                matcher = pattern.matcher(jsonStr);
                while (matcher.find()) // 继续向下匹配直到没有匹配到
                {
                    if (NodeHierarchyNum(jsonStr, matcher.end()) == 1) {
                        posEnd = matcher.end();
                        return jsonStr.substring(posStart, posEnd);
                    }
                }
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String[] getStrings(String key) throws Exception {
        // (?<=StringArray":\s{0,10}\[)[\w\W]*?(?=\])
        // "StringArray": ["Shenzhen", "Beijing", "Nanjing", "Guangzhou"],
        // 匹配上面的 "Shenzhen", "Beijing", "Nanjing", "Guangzhou"

        List<String> strings = new ArrayList<>();
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                String str = matcher.group();
                if (str.length() > 0) {
                    str = str.substring(1, str.length() - 1);
                    return str.split("\",\"");
                }
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public List<Integer> getInts(String key) throws Exception {
        // (?<=IntArray":\s{0,10}\[)[0-9,\s]*?(?=\])
        // "array":[11,32, 45,56,16,045]
        // 匹配上面的 11,32, 45,56,16,045

        // [0-9]+\b
        // 11,32, 45,56,16,045
        // 匹配上面的  11 32 45 56 16 045

        List<Integer> ints = new ArrayList<Integer>();
        String str = "";
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[0-9,\\s]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                str = matcher.group();
                pattern = Pattern.compile("[0-9]+\\b");
                matcher = pattern.matcher(str);
                while (matcher.find()) // 继续向下匹配知道没有匹配到
                {
                    ints.add(Integer.valueOf(matcher.group()));
                }
                return ints;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public List<Boolean> getBools(String key) throws Exception {
        // (?<=BoolAray":\s{0,10}\[)((true|false)\b|,|\s)*?(?=\])
        // "BoolAray":[false,false,true,true, false,truefalse t]
        // 匹配上面的 false,false,true,true, false,truefalse t

        // (?<!\B)(true|false)\b
        // false,false,true,true, false,truefalse t
        // 匹配上面的  false false true true false

        List<Boolean> booleans = new ArrayList<>();
        String str = "";
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)((true|false)\\b|,|\\s)*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                str = matcher.group();
                pattern = Pattern.compile("(?<!\\B)(true|false)\\b");
                matcher = pattern.matcher(str);
                while (matcher.find()) // 继续向下匹配知道没有匹配到
                {
                    booleans.add(Boolean.valueOf(matcher.group()));
                }
                return booleans;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public List<Float> getFloats(String key) throws Exception {
        // (?<=FloatArray":\s{0,10}\[)[\w\W]*?(?=\])
        // "FloatArray":[0.1,0.2,0.6,0.6,0.8,0.8,10.65],
        // 匹配上面的 0.1,0.2,0.6,0.6,0.8,0.8,10.65

        // \d+(\.\d*)?
        // 0.1,0.2,0.6,0.6,0.8,0.8,10.65
        // 匹配上面的  0.1,0.2,0.6,0.6,0.8,0.8,10.65

        List<Float> floats = new ArrayList<>();
        String str = "";
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                str = matcher.group();
                pattern = Pattern.compile("\\d+(\\.\\d*)?");
                matcher = pattern.matcher(str);
                while (matcher.find()) // 继续向下匹配直到没有匹配到
                {
                    floats.add(Float.valueOf(matcher.group()));
                }
                return floats;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String[] getJsonObjs(String key) throws Exception {
        // (?<=objs":\s{0,10}\[)[\w\W]*?(?=\])
        // "objs":
        //	[
        //		{"name":"小白虫","age":18,"married":false},
        //		{"name":"小黑虫","age":20,"married":false},
        //		{"name":"号地块","age":25,"married":true},
        //		{"name":"来接你","age":10,"married":true},
        //		{"name":"美女呢","age":21,"married":false},
        //		{"name":"送给你","age":26,"married":true}
        //	]
        // 匹配上面的
        //      {"name":"小白虫","age":18,"married":false},
        //		{"name":"小黑虫","age":20,"married":false},
        //		{"name":"号地块","age":25,"married":true},
        //		{"name":"来接你","age":10,"married":true},
        //		{"name":"美女呢","age":21,"married":false},
        //		{"name":"送给你","age":26,"married":true}

        List<String> strings = new ArrayList<>();
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                String str = matcher.group();
                patternStr="(?<=\\}),(?=\\{)";//匹配左右大括号中间的,逗号
                return str.split(patternStr);
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    //endregion
    //region set
    public String setBool(String key, boolean value) throws Exception {
        // (?<=Bool":\s{0,10})(true|false)\b
        // "Bool": false,
        // 匹配上面的false
        String patternStr = "(?<=" + key + "\":\\s{0,10})(true|false)\\b";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setInt(String key, int value) throws Exception {
        // (?<=Int":\s{0,10})[0-9]+
        // "Int":30,
        // 匹配上面的 30
        String patternStr = "(?<=" + key + "\":\\s{0,10})[0-9]+";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setString(String key, String value) throws Exception {
        // (?<=String":\s{0,10}\")[\w\W]*?(?=\")
        // "String":"HelloWorld",
        // 匹配上面的 HelloWorld
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\\")[\\w\\W]*?(?=\\\")";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setFloat(String key, float value) throws Exception {
        // (?<=Float":\s{0,10})\d+(\.\d*)?
        // "Float":12656.501,
        // 匹配上面的 12656.501
        String patternStr = "(?<=" + key + "\":\\s{0,10})\\d+(\\.\\d*)?";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setJsonObj(String key, String _json) throws Exception {
        int posStart = 0;
        int posEnd = 0;
        String patternStr = "\"" + key + "\":";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                posStart = matcher.end();
                pattern = Pattern.compile("\\}");
                matcher = pattern.matcher(jsonStr);
                while (matcher.find()) // 继续向下匹配直到没有匹配到
                {
                    if (NodeHierarchyNum(jsonStr, matcher.end()) == 1) {
                        posEnd = matcher.end();
                        jsonStr = jsonStr.substring(0, posStart) + _json + jsonStr.substring(posEnd, jsonStr.length());
                        return jsonStr;
                    }
                }
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setStrings(String key, List<String> values) throws Exception {
        // (?<=StringArray":\s{0,10}\[)[\w\W]*?(?=\])
        // "StringArray": ["Shenzhen", "Beijing", "Nanjing", "Guangzhou"],
        // 匹配上面的 "Shenzhen", "Beijing", "Nanjing", "Guangzhou"

        String value = "";
        for (int i = 0; i < values.size(); i++) {
            value += "\"" + values.get(i) + "\"";
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setInts(String key, List<Integer> values) throws Exception {
        // (?<=IntArray":\s{0,10}\[)[0-9,\s]*?(?=\])
        // "array":[11,32, 45,56,16,045]
        // 匹配上面的 11,32, 45,56,16,045

        String value = "";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[0-9,\\s]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setBools(String key, List<Boolean> values) throws Exception {
        // (?<=BoolAray":\s{0,10}\[)((true|false)\b|,|\s)*?(?=\])
        // "BoolAray":[false,false,true,true, false,truefalse t]
        // 匹配上面的 false,false,true,true, false,truefalse t

        String value = "";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)((true|false)\\b|,|\\s)*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setFloats(String key, List<Float> values) throws Exception {
        // (?<=FloatArray":\s{0,10}\[)[\w\W]*?(?=\])
        // "FloatArray":[0.1,0.2,0.6,0.6,0.8,0.8,10.65],
        // 匹配上面的 0.1,0.2,0.6,0.6,0.8,0.8,10.65

        String value = "";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        String patternStr = "(?<=" + key + "\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String setJsonObjs(String key,List<String> values) throws Exception{
        // (?<=objs":\s{0,10}\[)[\w\W]*?(?=\])
        // "objs":
        //	[
        //		{"name":"小白虫","age":18,"married":false},
        //		{"name":"小黑虫","age":20,"married":false},
        //		{"name":"号地块","age":25,"married":true},
        //		{"name":"来接你","age":10,"married":true},
        //		{"name":"美女呢","age":21,"married":false},
        //		{"name":"送给你","age":26,"married":true}
        //	]
        // 匹配上面的
        //      {"name":"小白虫","age":18,"married":false},
        //		{"name":"小黑虫","age":20,"married":false},
        //		{"name":"号地块","age":25,"married":true},
        //		{"name":"来接你","age":10,"married":true},
        //		{"name":"美女呢","age":21,"married":false},
        //		{"name":"送给你","age":26,"married":true}

        String value = "";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        String patternStr = "(?<="+key+"\":\\s{0,10}\\[)[\\w\\W]*?(?=\\])";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find()) {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + value + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    //endregion
    //region add
    public String addBool(String key, boolean value) throws Exception {
        String _value = "{\"" + key + "\":" + value + ",";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(_value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addInt(String key, int value) throws Exception {
        String _value = "{\"" + key + "\":" + value + ",";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(_value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addString(String key, String value) throws Exception {
        String _value = "{\"" + key + "\":\"" + value + "\",";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(_value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addFloat(String key, float value) throws Exception {
        String _value = "{\"" + key + "\":" + value + ",";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(_value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addJsonObj(String key, String _json) throws Exception {
        return addString(key, _json);
    }

    public String addBools(String key, List<Boolean> values) throws Exception {
        String value = "{\"" + key + "\":[";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        value += "],";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addInts(String key, List<Integer> values) throws Exception {
        String value = "{\"" + key + "\":[";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        value += "],";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addStrings(String key, List<String> values) throws Exception {
        String value = "{\"" + key + "\":[";
        for (int i = 0; i < values.size(); i++) {
            value += "\"" + values.get(i) + "\"";
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        value += "],";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addFloats(String key, List<Float> values) throws Exception {
        String value = "{\"" + key + "\":[";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        value += "],";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String addJsonObjs(String key,List<String> values) throws Exception{
        String value = "{\"" + key + "\":[";
        for (int i = 0; i < values.size(); i++) {
            value += values.get(i);
            if (i != values.size() - 1) {
                value += ",";
            }
        }
        value += "],";
        String patternStr = "\\{";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            return matcher.replaceFirst(value);    //匹配首个{进行替换
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    //endregion
    //region remove
    public String removeBool(String key) throws Exception {
        // "setBoole":\s{0,10}(true|false)\b\s*,?\s*
        // 匹配 "native_enable": true,
        String patternStr = "\"" + key + "\":\\s{0,10}(true|false)\\b\\s*,?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeInt(String key) throws Exception {
        // "native_interstitial_interval":\s{0,10}[0-9]+\s*,?\s*
        // 匹配 "native_interstitial_interval": 30,
        String patternStr = "\"" + key + "\":\\s{0,10}[0-9]+\\s*,?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeString(String key) throws Exception {
        // "String":\s{0,10}\"[\w\W]*?",?
        String patternStr = "\"" + key + "\":\\s{0,10}\\\"[\\w\\W]*?\",?";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeFloat(String key) throws Exception {
        // "Float":\s{0,10}\d+(\.\d*)?,?\s*
        String patternStr = "\"" + key + "\":\\s{0,10}\\d+(\\.\\d*)?,?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeJsonObj(String key) throws Exception {
        int posStart = 0;
        int posEnd = 0;
        String patternStr = "\"" + key + "\":";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        if (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                posStart = matcher.end() - key.length() - 3;
                pattern = Pattern.compile("\\}");
                matcher = pattern.matcher(jsonStr);
                while (matcher.find()) // 继续向下匹配直到没有匹配到
                {
                    if (NodeHierarchyNum(jsonStr, matcher.end()) == 1) {
                        print(jsonStr.charAt(matcher.end()) + "");
                        if (jsonStr.charAt(matcher.end()) == ',') {
                            posEnd = matcher.end() + 1;
                        } else {
                            posEnd = matcher.end();
                        }
                        jsonStr = jsonStr.substring(0, posStart) + jsonStr.substring(posEnd, jsonStr.length());
                        return jsonStr;
                    }
                }
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeBools(String key) throws Exception {
        // "BoolAray":\s{0,10}\[((true|false)\b|,|\s)*?(?=\])]\s*,?\s*
        // 匹配 "fd": [ false, true, false, true, true ],
        String patternStr = "\"" + key + "\":\\s{0,10}\\[((true|false)\\b|,|\\s)*?(?=\\])]\\s*,?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeInts(String key) throws Exception {
        // "IntArray":\s{0,10}\[[0-9,\s]*?(?=\])]\s*.?\s*
        // 匹配 "IntArray": [ 12, 56, 854, 40,6506, 560, 450, 4650],
        String patternStr = "\"" + key + "\":\\s{0,10}\\[[0-9,\\s]*?(?=\\])]\\s*.?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeStrings(String key) throws Exception {
        // "StringArray":\s{0,10}\[[\w\W]*?\]\s*,?\s*
        // 匹配 "StringArray": ["Shenzhen","Beijing","Nanjing","Guangzhou"],
        String patternStr = "\"" + key + "\":\\s{0,10}\\[[\\w\\W]*?\\]\\s*,?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeFloats(String key) throws Exception {
        // "FloatArray":\s{0,10}\[[\w\W]*?\],?\s*
        String patternStr = "\"" + key + "\":\\s{0,10}\\[[\\w\\W]*?\\],?\\s*";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(jsonStr);
        while (matcher.find())//匹配成功
        {
            if (NodeHierarchyNum(jsonStr, matcher.start()) == 1) {
                jsonStr = jsonStr.substring(0, matcher.start()) + jsonStr.substring(matcher.end(), jsonStr.length());
                return jsonStr;
            }
        }
        throw new Exception("Key:" + key + ":解析失败");
    }

    public String removeJsonObjs(String key) throws Exception{
       return removeStrings(key);
    }
    //endregion
    //region Util
    private static void print(String msg) {
        Log.d("JsonUtil:", msg);
    }

    // _json : json 格式字符串
    // pos   : 节点在_json 位置
    // return: 返回所在位置的层级。小于等于0:表示解析失败;1:表示顶级层级(根节点),2:表示二级层级;3:表示三级层级;以此类推......
    private static int NodeHierarchyNum(String _json, int pos) {
        _json = _json.substring(0, pos);
        int braceL = 0;   // 左括号数量
        int braceR = 0;   // 右括号数量
        //region ******************* 移除引号内容 ***************************
        // "[\s\S]*?"
        String patternStr = "\"[\\s\\S]*?\"";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(_json);
        _json = matcher.replaceAll("");
        //endregion
        //region ******************* 左右括号计数 ***************************
        patternStr = "\\{";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(_json);
        while (matcher.find()) {
            braceL++;
        }
        patternStr = "\\}";
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(_json);
        while (matcher.find()) {
            braceR++;
        }
        //endregion
        return braceL - braceR;
    }
    //endregion
}

posted @ 2022-07-20 20:13  镜子-眼泪  阅读(473)  评论(0)    收藏  举报