关联资源
实现效果
工具类实现 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.youkuaiyun.com/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路径,直到最后一层的key
JsonNode 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就能取到最后一层