解析json串,利用正则表达式,split

时间:2021-11-01 14:28:38

public class SplitJson {

public static void main(String[] args) {
        // TODO Auto-generated method stub
     String str = "[{\"version\":\"100\"},{\"type\":\"210\"},{\"chanl_no\":\"30\"},{\"chanl_sub_no\":\"3001\"},{\"chanl_date\":\"\"},{\"chanl_time\":\"\"},{\"ectip_date\":\"\"},{\"chanl_flow_no\":\"\"},{\"ectip_flow_no\":\"\"},{\"chanl_trad_no\":\"3FC012\"},{\"term_inf\":\"\"},{\"resp_code\":\"\"},{\"resp_msg\":\"\"},{\"page\":\"\"},{\"maxrow\":\"\"},{\"locstr\":\"\"},{\"tot_rec\":\"\"},{\"ARRAY_3FC012\":\"\"},{\"0\":\"\"},{\"age\":\"23\"},{\"name\":\"小cn\"},{\"sex\":\"男\"},{\"1\":\"\"},{\"sex\":\"女\"},{\"age\":\"24\"},{\"name\":\"小王\"},{\"29\":\"\"},{\"name\":\"小张\"},{\"age\":\"22\"},{\"sex\":\"男\"}]";
     //正则表达式的串为{\"29\":\"\"}
     String[] splitStr = str.split("\\{\\\"\\d{1,2}\\\":\\\"\\\"\\}");
     String resultStr = splitStr[0];
     for(int i = 1; i < splitStr.length; i++){
         resultStr += splitStr[i].replaceAll("\\},\\{", ",").substring(1);//去掉多余逗号
     }
     System.out.println(str);
     System.out.println(resultStr);
     //测试空指针异常
     System.out.println(spitJson(null, null));
     System.out.println(spitJson("", null));
     System.out.println(spitJson("", ""));
    }
    
    public static String spitJson(String jsonStr, String regex){
        if(jsonStr == null || regex == null ) return "";
        String[] splitStr = jsonStr.split(regex);
        String resultStr = splitStr[0];
        
        return resultStr;
    }

}