java正则表达式获取json字符串中指定key的value

<仅支持取JSON字符串中, 简单属性值的配置, 即值内容中不包含\[\]或{}格式的数据>

import org.apache.commons.lang3.StringEscapeUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class JsonAttributeFormatTest {

public static void main(String\[\] args) {

String parem = "{ \" param \" :{ \" song_id \" : \" 10023423001 \" }, \" param2 \" :{ \" song_id \" : \" 10023423001 \" , \" sec_code \" : \" 000001 \" , \" sec_short_name \" : \" 万科A \" }, \" param3 \" :{ \" song_id \" : \" 10023423001 \" , \" sec_code \" : \" 000001 \" , \" sec_short_name \" : \" 万科A \" , \" arrtibutes \" :{ \" id \" :2955, \" path \" : \" /file/word \" , \" fileType \" : \" xml \" }}, \" param4 \" :{ \" song_id \" : \" 10023423001 \" , \" sec_code \" : \" 000001 \" , \" sec_short_name \" : \" 万科A \" , \" arrtibutes \" :{ \" id \" :2955, \" path \" : \" /file/word \" , \" fileType \" : \" xml \" , \" arrtibutes2 \" :{ \" id \" :2955, \" path \" : \" /file/word \" , \" fileType \" : \" xml \" }}}, \" param5 \" :{ \" song_id \" : \" 10023423001 \" , \" sec_code \" : \" 000001 \" , \" arrtibutes \" :{ \" id \" :2955, \" path \" : \" /file/word \" , \" fileType \" : \" xml \" }, \" sec_short_name \" : \" 万科A \" }, \" paramList \" :**** ****\\"**** ****name**** ****\\"**** ****,**** ****\\"**** ****work**** ****\\"**** ****,**** ****\\"**** ****good**** ****\\"**** ****, \" paramList2 \" :2,4,6,7, \" paramList3 \" :{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****}, \" paramList4 \" :{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****},{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****,**** ****\\"**** ****sec_code**** ****\\"**** ****:**** ****\\"**** ****000001**** ****\\"**** ****,**** ****\\"**** ****sec_short_name**** ****\\"**** ****:**** ****\\"**** ****万科A**** ****\\"**** ****}, \" parameter \" :{ \" biz_code \" : \" 10023423001 \" , \" biz_title \" : \" 是东风风光 \" , \" userList \" :{**** ****\\"**** ****name**** ****\\"**** ****:**** ****\\"**** ****张三**** ****\\"**** ****,**** ****\\"**** ****phone**** ****\\"**** ****:12355566},{**** ****\\"**** ****name**** ****\\"**** ****:**** ****\\"**** ****李四**** ****\\"**** ****,**** ****\\"**** ****phone**** ****\\"**** ****:1567889}}, \" address \" :null, \" type \" : \"\" , \" song_id \" : \" 132430001 \" }" ;

parem = StringEscapeUtils.unescapeJava (parem);

System.out .println(getFieldListFromJsonStr (parem,"id" ));

}

public static List<String> getFieldListFromJsonStr(String jsonStr, String fieldName) {

List<String> fieldValues = new ArrayList<>();

String regex = "(?<=( \" " + fieldName + " \" :)).*?(?=(,| \\ }))" ; //单属性配置,且内容中不包含\[\]或{}格式数据

Pattern pattern = Pattern.compile (regex);

Matcher matcher = pattern.matcher(jsonStr);

while (matcher.find()) {

if (StringUtils.isNotEmpty (matcher.group().trim())) {

fieldValues.add(matcher.group().trim());

}

}

return fieldValues;

}

}

<在JSON字符串中,通过指定属性名称, 获取任意格式的数据>

import org.apache.commons.lang3.StringEscapeUtils;

import org.springframework.util.StringUtils;

import java.util.HashMap;

import java.util.LinkedList;

import java.util.Map;

/**

* jlZhang.oth

*/

public class JsonHandler {

public static void main(String\[\] args) {

String str = "{ \" param \" :{ \" song_id \" : \" 10023423001 \" }, \" param2 \" :{ \" song_id \" : \" 10023423006 \" , \" sec_code \" : \" 000001 \" , \" sec_short_name \" : \" 万科A \" }, \" param3 \" :{ \" song_id \" : \" 10023423001 \" , \" sec_code \" : \" 000001 \" , \" sec_short_name \" : \" 万科A \" , \" arrtibutes \" :{ \" id \" :2955, \" path \" : \" /file/word \" , \" fileType \" : \" xml \" }}, \" paramList \" :**** ****\\"**** ****name**** ****\\"**** ****,**** ****\\"**** ****work**** ****\\"**** ****,**** ****\\"**** ****good**** ****\\"**** ****, \" paramList2 \" :2,4,6,7, \" paramList3 \" :{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****}, \" paramList4 \" :{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****},{**** ****\\"**** ****song_id**** ****\\"**** ****:**** ****\\"**** ****10023423001**** ****\\"**** ****,**** ****\\"**** ****sec_code**** ****\\"**** ****:**** ****\\"**** ****000001**** ****\\"**** ****,**** ****\\"**** ****sec_short_name**** ****\\"**** ****:**** ****\\"**** ****万科A**** ****\\"**** ****}, \" parameter \" :{ \" biz_code \" : \" 10023423001 \" , \" biz_title \" : \" 是东风风光 \" , \" userList \" :{**** ****\\"**** ****name**** ****\\"**** ****:**** ****\\"**** ****张三**** ****\\"**** ****,**** ****\\"**** ****phone**** ****\\"**** ****:12355566},{**** ****\\"**** ****name**** ****\\"**** ****:**** ****\\"**** ****李四**** ****\\"**** ****,**** ****\\"**** ****phone**** ****\\"**** ****:1567889}}, \" address \" :null, \" type \" : \"\" , \" song_iddd \" :true}" ;

String result = getFiledValueFromJsonStr (str, "arrtibutes" , 300);

System.out .println(result);

}

private static String getFiledValueFromJsonStr(String jsonStr, String fieldName, Integer orderFindNumber) {

if (StringUtils.isEmpty (jsonStr) || StringUtils.isEmpty (fieldName)) {

return "" ;

}

orderFindNumber = (orderFindNumber == null || orderFindNumber <= 1) ? 1 : orderFindNumber;

jsonStr = StringEscapeUtils.unescapeJava (jsonStr);

char \[\] jsonChar = jsonStr.toCharArray();

// 封装\[\]以及{}的定位信息

Map<Integer, Integer> mapIndex = new HashMap<Integer, Integer>(); // 记录成对{}的索引

Map<Integer, Integer> listIndex = new HashMap<Integer, Integer>(); // 记录成对\[\]的索引

Boolean strFlag = null ;

LinkedList<Integer> mapMark = new LinkedList<>();

LinkedList<Integer> listMark = new LinkedList<>();

for (int i = 0; i < jsonChar.length ; i++) {

char c = jsonChari;

if (c == ' ' ) {

continue ;

} else if (c == '"' ) {

if (strFlag != null && strFlag == true ) {

strFlag = null ;

} else {

strFlag = true ;

}

}

if (strFlag == null ) {

if (c == '{' ) {

mapMark.add(i);

} else if (c == '}' ) {

mapIndex.put(mapMark.getLast(), i);

mapMark.removeLast();

} else if (c == '[' ) {

listMark.add(i);

} else if (c == ']' ) {

listIndex.put(listMark.getLast(), i);

listMark.removeLast();

}

}

}

// 定位该属性名称的索引位置

StringBuilder attrSb = new StringBuilder();

attrSb.append(" \" " ).append(fieldName).append(" \" " );

int nameLocation = 0;

for (int i = 0; i < orderFindNumber; i++) {

if (nameLocation == 0) {

if (jsonStr.indexOf(attrSb.toString()) == -1) return "" ; // 首个属性名没设置直接返回

nameLocation = jsonStr.indexOf(attrSb.toString());

} else {

if (jsonStr.indexOf(attrSb.toString(), nameLocation + 1) == -1) continue ; // 后续没找到取上一个属性名

nameLocation = jsonStr.indexOf(attrSb.toString(), nameLocation + 1);

}

}

int markLocation = jsonStr.indexOf(":" , nameLocation);

LinkedList<Integer> strIndex = new LinkedList<>();

LinkedList<Integer> cutOut = new LinkedList<>();

for (int i = markLocation + 1; i < jsonChar.length ; i++) {

char c = jsonChari;

if (c == ' ' ) {

continue ;

} else if (c == '"' ) {

if (strIndex.size() == 0) {

strIndex.add(i);

} else {

strIndex.add(i + 1);

cutOut.addAll(strIndex);

break ;

}

}

if (strIndex.size() == 0) {

if ("n" .equalsIgnoreCase(String.valueOf (c)) || "f" .equalsIgnoreCase(String.valueOf (c)) || "t" .equalsIgnoreCase(String.valueOf (c))) {

// null, false, true值

cutOut.add(i);

int last = (jsonStr.indexOf(":" , i) == -1) ? jsonStr.length() - 1 : jsonStr.indexOf("," , i);

// 排除格式: ..."cache":null}],

while (jsonCharlast == '}' || jsonCharlast == ']' || jsonCharlast == ',' ) {

last = last - 1;

}

cutOut.add(last + 1);

break ;

}

if (Character.isDigit (c)) {

cutOut.add(i);

int last = (jsonStr.indexOf(":" , i) == -1) ? jsonStr.length() - 1 : jsonStr.indexOf("," , i);

// 排除格式: ..."cache":456}],

while (jsonCharlast == '}' || jsonCharlast == ']' || jsonCharlast == ',' ) {

last = last - 1;

}

cutOut.add(last + 1);

break ;

}

if (c == '{' ) {

Integer last = mapIndex.get(i);

if (null != last) {

cutOut.add(i);

cutOut.add(last + 1);

}

break ;

} else if (c == '[' ) {

Integer last = listIndex.get(i);

if (null != last) {

cutOut.add(i);

cutOut.add(last + 1);

}

break ;

}

}

}

// 获取最终的结果

if (cutOut.size() == 0) return "" ;

String result = jsonStr.substring(cutOut.getFirst(), cutOut.getLast());

return result;

}

}

相关推荐
hj28625116 分钟前
Linux 网络服务综合笔记(概念 + 命令 + 实操案例)2
linux·运维·网络
what_201817 分钟前
Linux 磁盘 (查看、划分、inode)
linux·运维·服务器
ai_coder_ai24 分钟前
论 NoSQL 数据库技术及其应用
数据库·nosql
27399202937 分钟前
GDB调试(Linux)
linux
凡人叶枫1 小时前
Effective C++ 条款23:宁以 non-member、non-friend 替换 member 函数
linux·开发语言·c++·嵌入式开发
不会C语言的男孩1 小时前
Linux 系统编程 · 第 4 章:文件属性与元数据
linux·c语言·开发语言
小生不才yz1 小时前
Shell脚本精读 · S02-03 | 词拆分、通配符与未加引号的变量
linux
2601_961845421 小时前
法考真题及答案解析|历年真题|资料已整理
linux·windows·ubuntu·macos·centos·gnu
A_humble_scholar2 小时前
Linux(七)调度器:从硬件矛盾到进程切换的底层逻辑
linux·服务器·网络
AOwhisky2 小时前
Redis 学习笔记(第一期):概述、安装配置与核心理论
运维·数据库·redis·笔记·学习·云计算