Json取值工具类
Posted JavaQ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Json取值工具类相关的知识,希望对你有一定的参考价值。
喜欢总结一些工作中写的代码,将部分代码抽离出来,形成一个小的工具类或者jar包,方便在各个项目中使用,这样时间久了、总结的多了就形成了自己的代码库,这些都是自己的资源。本篇将总结一个从Json字符串中直接取指定key值的工具类,详细代码如下:
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.junit.Test;
public class JsonValueTool {
@Test
public void test() {
String originString = "{\n" +
" \"student\": [\n" +
" {\n" +
" \"name\": \"jack\", \n" +
" \"age\": 25, \n" +
" \"education\": {\n" +
" \"education1\": \"Harvard University\", \n" +
" \"education2\": \"University of Cambridge\", \n" +
" \"education3\": \"Massachusetts Institue of Technology\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
JSONObject originObject = JSONObject.parseObject(originString);
System.out.println(JsonValueTool.getValueByKeyExpression(originObject, "student", "student#education#education2"));
}
public static Object getValueByKeyExpression(Object originObject, String startKey, String targetKeyExpression) {
if (Strings.isNullOrEmpty(startKey)) {
return originObject;
}
if (originObject instanceof JSONObject) {
return getValueFromJSONObjectByKeyExpression((JSONObject) originObject, startKey, targetKeyExpression);
}
if (originObject instanceof JSONArray) {
return getValueFromJSONArrayByKeyExpression((JSONArray) originObject, startKey, targetKeyExpression);
}
return null;
}
private static String getNextKey(String startKey, String targetKeyExpression) {
if (Strings.isNullOrEmpty(targetKeyExpression)) {
return null;
}
String[] keys = targetKeyExpression.split("#");
for (int i = 0; i < keys.length; i++) {
if (keys[i].equals(startKey) && (i < keys.length - 1)) {
return keys[i + 1];
}
}
return null;
}
private static Object getValueFromJSONArrayByKeyExpression(JSONArray originObject, String startKey, String targetKeyExpression) {
for (int j = 0; j < originObject.size(); j++) {
JSONObject jsonObject = originObject.getJSONObject(j);
Object targetObject = getValueFromJSONObjectByKeyExpression(jsonObject, startKey, targetKeyExpression);
if (targetObject != null) {
return targetObject;
}
}
return null;
}
private static Object getValueFromJSONObjectByKeyExpression(JSONObject originObject, String startKey, String targetKeyExpression) {
Object object = originObject.get(startKey);
return object != null ? getValueByKeyExpression(object, getNextKey(startKey, targetKeyExpression), targetKeyExpression) : null;
}
}
示例单元测试将输出:University of Cambridge
以上是关于Json取值工具类的主要内容,如果未能解决你的问题,请参考以下文章
Java常用工具类---image图片处理工具类Json工具类
Java常用工具类---image图片处理工具类Json工具类
HttpClientUntils工具类的使用及注意事项(包括我改进的工具类和Controller端的注意事项附 Json 工具类)