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 = jsonChar[i];

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 = jsonChar[i];

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 (jsonChar[last] == '}' || jsonChar[last] == ']' || jsonChar[last] == ',') {

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 (jsonChar[last] == '}' || jsonChar[last] == ']' || jsonChar[last] == ',') {

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;

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/682447.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【ASP.NET 6 Web Api 全栈开发实战】--前言

《ASP.NET 6 Web Api 实战》专栏通过一步一步的开发并完善一个记账软件项目&#xff0c;来引导大家学习相关的知识&#xff0c;其中的知识包括但不限于如下内容&#xff1a; Web Api 开发.NET 6 项目微服务架构的搭建身份认证移动端应用开发more。。。 专栏结构 专栏分为单体…

分享88个CSS3特效,总有一款适合您

分享88个CSS3特效&#xff0c;总有一款适合您 88个CSS3特效下载链接&#xff1a;https://pan.baidu.com/s/1pDAyFESnO8HSnCZj4-DOzQ?pwd8888 提取码&#xff1a;8888 Python采集代码下载链接&#xff1a;采集代码.zip - 蓝奏云 学习知识费力气&#xff0c;收集整理更不…

STM32CubeMX中外部中断的配置和使用指南

使用STM32CubeMX进行外部中断&#xff08;External Interrupt&#xff09;的配置和使用对于STM32微控制器开发非常重要。外部中断可以让微控制器在外部事件发生时及时作出反应&#xff0c;例如按键触发、传感器信号等。通过STM32CubeMX的图形化界面&#xff0c;开发人员可以轻松…

第13章 网络 Page724 asio定时器

程序代码&#xff1a; 11行&#xff0c;声明一个ios对象 13行&#xff0c;使用ios对象作为参数声明一个定时器&#xff0c;此时&#xff0c;定时器和ios完成了关联&#xff0c;后面定时器如果有任务的话&#xff0c;就可以将任务交给ios 16行&#xff0c;为定时器设置一个定…

力扣-125. 验证回文串

文章目录 力扣题目代码 力扣题目 如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后&#xff0c;短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。 字母和数字都属于字母数字字符。 给你一个字符串 s&#xff0c;如果它是 回文串 &#xff0c;…

【日常聊聊】新年新征程:迎接学习的挑战

&#x1f34e;个人博客&#xff1a;个人主页 &#x1f3c6;个人专栏&#xff1a;日常聊聊 ⛳️ 功不唐捐&#xff0c;玉汝于成 目录 前言 正文 结语 我的其他博客 前言 随着新的一年的到来&#xff0c;程序员们站在了全新的起点。这是一个充满机遇和挑战的时刻&#xff0…

【JavaEE】_HTTP请求与响应

目录 1. HTTP协议 1.1 HTTP简介 1.2 Fiddler 2. HTTP请求 2.1 首行 2.2 请求头&#xff08;header&#xff09; 2.3 空行 2.4 正文&#xff08;body&#xff09; 3. HTTP响应 3.1 首行 3.2 响应头&#xff08;header&#xff09; 3.3 空行 3.4 正文&#xff08;bo…

13.let、const、var的区别

&#xff08;1&#xff09;块级作用域&#xff1a; 块作用域由 { }包括&#xff0c;let和const具有块级作用域&#xff0c;var不存在块级作用域。块级作用域解决了ES5中的两个问题&#xff1a; 内层变量可能覆盖外层变量用来计数的循环变量泄露为全局变量 &#xff08;2&…

51单片机编程基础(C语言):LED点阵屏

点阵屏介绍 类似于数码管&#xff0c;要用到肉眼视觉效应。扫描&#xff0c;才能把每一个LED都能选中&#xff0c;从而显示我们想要的图形&#xff0c;否则&#xff0c; 只能一次点亮一个LED&#xff0c; LED使用 51单片机点阵屏电路图&#xff1a; 实际连接顺序如下图&#…

Java中的乐观锁和悲观锁

使用场景及用法 悲观锁 总是假设最坏的情况&#xff0c;每次去拿数据的时候都认为别人会修改&#xff0c;所以每次在拿数据的时候都会上锁&#xff0c;这样别人想拿这个数据就会阻塞直到它拿到锁&#xff08;共享资源每次只给一个线程使用&#xff0c;其它线程阻塞&#xff0c;…

爱快使用VPN

文章目录 一、VPN服务器1. 各种VPN比较2. PPTP服务端配置3. 创建登录账号4. 创建端口映射5. 设置动态域名 二、Windows客户端1. 连接配置2. 不能连接 Internet 配置 一、VPN服务器 1. 各种VPN比较 PPTPIPSECOpenVPN简介微软推出的VPN协议&#xff0c;占用资源少更高级的VPN协…

php基础学习之分支结构和循环结构(不细讲,来对比一下和两大常用高级编程语言(C++/Java)的细微区别以便记忆)

分支结构 常见分支结构 编程语言常见分支结构有&#xff1a; if语句if-else语句if-elseif-else语句switch语句 其中&#xff0c;除了if-elseif-else语句外&#xff0c;另外3中分支语句在php中和C/Java是一模一样的&#xff01; 而if-elseif-else的唯一不同点就在&#xff0c;【…

Linux查看日志的几种方法总结

摘要 Linux系统中查看日志的命令确实多种多样&#xff0c;每个命令都有其特定的用途和优势。常用的命令有&#xff1a;tail、cat、tac、head、echo&#xff0c;grep、less、awk、sed。 下面我会详细解释这些命令在查看日志时的用法和特点&#xff1a; tail命令&#xff1a; ta…

机器学习:ROC曲线笔记

ROC曲线&#xff08;Receiver Operating Characteristic Curve&#xff09;是一种用于评估二分类模型性能的图形化工具&#xff0c;主要用于展示在不同阈值&#xff08;Threshold&#xff09;下模型的真阳性率&#xff08;True Positive Rate&#xff0c;TPR&#xff09;和假阳…

比亚迪面试

HashMap的底层结构 HashMap 在 Java 中是基于散列算法实现的&#xff0c;其底层主要由数组和链表&#xff08;Java 8 后加入了红黑树&#xff09;构成。当一个元素被加入到 HashMap 中时&#xff0c;会使用散列函数计算出该元素的存储索引&#xff0c;然后将元素存储到对应索引…

elasticSearch使用场景深入详解

Elasticsearch 是一个基于 Lucene 的搜索引擎&#xff0c;它提供了一个分布式、支持多租户的全文搜索引擎&#xff0c;具有 HTTP Web 接口和无模式 JSON 文档。Elasticsearch 是 Elastic Stack 的核心&#xff0c;Elastic Stack 包括 Kibana、Beats 和 Logstash 等组件&#xf…

寒假作业:2024/2/14

作业1&#xff1a;编程实现二维数组的杨辉三角 代码&#xff1a; #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, const char *argv[]) {int n;printf("please enter n:");scanf("%d",&n);int a…

Windows 安装Redis教程

在Windows系统上安装Redis相对简单&#xff0c;主要步骤包括下载、解压、配置和启动Redis服务。以下是一个详细的安装教程&#xff1a; 1. 下载Redis 访问Redis官方网站下载页面&#xff1a;https://redis.io/download选择适用于Windows的安装包&#xff0c;通常有两个版本&a…

蓝桥杯---奇怪的数列

题目描述 从X星截获一份电码&#xff0c;是一些数字&#xff0c;如下&#xff1a; 13 1113 3113 132113 1113122113 .... YY博士经彻夜研究&#xff0c;发现了规律&#xff1a; 第一行的数字随便是什么&#xff0c;以后每一行都是对上一行“读出来” 比如第2行&#xff0c;是对…

springboot开启mybatis二级缓存

我的项目版本号如下&#xff1a; <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.8</version><relativePath/> <!-- lookup parent from reposito…