本文主要是介绍利用jackson的JsonNode封装工具类快速获取json字符串中任意节点的json数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 关联资源
- 实现效果
- 实现代码
- 实现思路梳理
关联资源
- 代码地址
- 视频讲解:
- 利用jackson中的JsonNode取值
- 封装工具类xxx.xxx.xx的方式取值
- 结合泛型封装工具类取值并返回对应类型
实现效果
工具类实现 xxx.xxx.xxx的形式直接从json字符串中获取任意节点字段的值,如下图所示:
实现代码
当前引入的jackson的依赖为:
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.10.1</version>
</dependency>
封装Json处理工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;/*** @author lzp* @Date:2023/3/1* @description: json处理工具类*/
public class MyJsonUtils {/*** 单例objectMapper,提高性能* 网上的性能测试:https://blog.csdn.net/qq_31960623/article/details/117778291*/private static final ObjectMapper objectMapper = new ObjectMapper();/*** 单例 饿汉式*/private static final MyJsonUtils INSTANCE = new MyJsonUtils();private MyJsonUtils() {}/*** 单例模式,暴露一个单例的工具类实例获取*/public static MyJsonUtils getInstance() {return INSTANCE;}/*** 通过key路径取到最后一级key对应的jsonNode** @param jsonStr 原始的json字符串* @param keyPath xx.xxx.xxx格式的key路径* @return*/public JsonNode getValueByKeyPath(String jsonStr, String keyPath) throws JsonProcessingException {JsonNode jsonNode = objectMapper.readTree(jsonStr);String[] paths = keyPath.split("\\.");// 遍历key路径,直到最后一层的keyJsonNode currentNode = jsonNode;for (String key : paths) {currentNode = currentNode.get(key);if (currentNode == null) {return null;}}return currentNode;}/*** 通过key路径取到最后一级key对应的value值** @param jsonStr 原始json字符串* @param keyPath xx.xxx.xxx格式的key路径* @param cls 值的对象类型*/public <T> T getValueByKeyPath(String jsonStr, String keyPath, Class<T> cls) throws JsonProcessingException {JsonNode jsonNode = this.getValueByKeyPath(jsonStr, keyPath);if (jsonNode == null) {return null;}return objectMapper.treeToValue(jsonNode, cls);}/*** 测试*/public static void main(String[] args) throws JsonProcessingException {String jsonStr = "{\"head\":{\"face\":\"隔壁老王的小脸\",\"eye\":{\"left\":\"轮回眼\",\"right\":\"写轮眼\"},\"iq\":250},\"body\":\"身材修长\",\"likeStudy\":true}";// 分别取到各个类型的值String valueStr = MyJsonUtils.getInstance().getValueByKeyPath(jsonStr, "head.eye.left", String.class);Integer valueInt = MyJsonUtils.getInstance().getValueByKeyPath(jsonStr, "head.iq", Integer.class);Boolean valueBool = MyJsonUtils.getInstance().getValueByKeyPath(jsonStr, "likeStudy", Boolean.class);System.out.println(valueStr);System.out.println(valueInt);System.out.println(valueBool);}}
实现思路梳理
关键代码就下面这块
- 先把字符串按 "."进行分割成数组
- 然后遍历key,注意每次循环的时候,currentNode = 下一个key的值,类似递归的思想,最后一次循环中的key就能取到最后一层
这篇关于利用jackson的JsonNode封装工具类快速获取json字符串中任意节点的json数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!