实现从JSON字符串中提取任意属性(包括数组)的Java方法,支持嵌套结构和多种数据类型
import java.util.regex.*;
public class HelloWorld {
public static void main(String[] args) {
// 示例1
String json1 = "{\"successflag\": true, \"ddd\":\"true\", \"voucher\":{\"bf\":[{\"cf\":\"1\"}]}}";
System.out.println(extractValueByRegex(json1, "billinfo"));
System.out.println(extractValueByRegex(json1, "cvoucherflow"));
System.out.println(extractValueByRegex(json1, "successflag"));
System.out.println(extractValueByRegex(json1, "ddd"));
System.out.println(extractValueByRegex(json1, "eeee"));
// 输出: [{"cvoucherflow":"1"}] 1 true true null
// 示例2
String json2 = "{\"billinfo\":[{\"cbillcode\":\"JK_001\"}]}";
System.out.println(extractValueByRegex(json2, "billinfo"));
// 输出: [{"cbillcode":"JK_001"}]
// 示例3
String json3 = "{\"returnCode\":[\"0000\",\"0001\"]}";
System.out.println(extractValueByRegex(json3, "returnCode"));
// 输出: ["0000","0001"]
}
/**
* 提取 JSON 字符串中指定属性的值(支持数组和嵌套)
* @param jsonStr JSON 字符串
* @param key 要提取的属性名(如 "billinfo")
* @return 属性值的字符串形式,若不存在则返回 null
*/
public static String extractValueByRegex(String jsonStr, String key) {
// 正则匹配:\"key\":\s*(\{[^{}]*\}|\[[^\[\]]*\]|\"[^\"]*\"|true|false|null|\d+\.?\d*)
String regex = "\"" + Pattern.quote(key) + "\"\\s*:\\s*(\\{[^{}]*\\}|\\[[^\\[\\]]*\\]|\"[^\"]*\"|true|false|null|\\d+\\.?\\d*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(jsonStr);
if (matcher.find()) {
String matchedValue = matcher.group(1);
// 去除字符串值的引号(如果是字符串类型)
if (matchedValue.startsWith("\"") && matchedValue.endsWith("\"")) {
return matchedValue.substring(1, matchedValue.length() - 1);
}
return matchedValue; // 直接返回布尔值/数字/null/数组
}
return null;
}
/**
* 提取 JSON 字符串中指定属性的值(支持数组和嵌套)
* @param jsonStr JSON 字符串
* @param key 要提取的属性名(如 "billinfo")
* @return 属性值的字符串形式,若不存在则返回 null
*/
public static List<String> extractValuesByRegex(String jsonStr, String key) {
List<String> values = new ArrayList<>();
// 正则匹配:\"key\":\s*(\{[^{}]*\}|\[[^\[\]]*\]|\"[^\"]*\"|true|false|null|\d+\.?\d*)
String regex = "\"" + Pattern.quote(key) + "\"\\s*:\\s*(\\{[^{}]*\\}|\\[[^\\[\\]]*\\]|\"[^\"]*\"|true|false|null|\\d+\\.?\\d*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(jsonStr);
while (matcher.find()) {
String matchedValue = matcher.group(1);
// 去除字符串值的引号(如果是字符串类型)
if (matchedValue.startsWith("\"") && matchedValue.endsWith("\"")) {
matchedValue = matchedValue.substring(1, matchedValue.length() - 1);
}
values.add(matchedValue);
}
return values;
}
}