如果项目需求是从某些复杂的json里面取值进行计算,用jsonpath+IK(ik-expression)来处理十分方便,jsonpath用来取json里面的值然后用IK自带的函数进行计算,如果是特殊的计算那就自定义IK方法搞定,配置化很方便.
下面简单介绍下jsonpath的使用方法,主要测试都在JsonPathDemo类里面:
下面是一个简单的java项目demo:
注意: 其中他的max,min,avg,stddev函数只能类似于如下处理:
context.read("$.avg($.result.records[0].loan_type,$.result.records[1].loan_type,$.result.records[2].loan_type)");
不能传入list 感觉比较鸡肋,如果传入list 他会报错(如下错误写法):
Object maxV = context.read("$.max($.result.records[*].loan_type)");
Object maxV = context.read("$.result.records[*].loan_type.max()");
报错信息都一样,如下:
Exception in thread "main" com.jayway.jsonpath.JsonPathException: Aggregation function attempted to calculate value using empty array
JsonPathDemo是一个测试demo:
public class JsonPathDemo {
public static void main(String[] args) {
String json = FileUtils.readFileByLines("demo.json");
ReadContext context = JsonPath.parse(json);
//1 返回所有name
List names = context.read("$.result.records[*].name");
//["张三","李四","王五"]
System.out.println(names);
//2 返回所有数组的值
List
pom文件引入:
<dependency>
<groupId>com.jayway.jsonpathgroupId>
<artifactId>json-pathartifactId>
<version>2.3.0version>
dependency>
其中demo.json是一个测试json:
{
"action": "/interface.service/xxx/queryBlackUserData",
"all": "1",
"result": {
"count": 2,
"tenant_count": 2,
"records": [
{
"name": "张三",
"pid": "500234199212121212",
"mobile": "18623456789",
"applied_at": "3",
"confirmed_at": "5",
"confirm_type": "overdue",
"loan_type": 1,
"test": "mytest",
"all": "2"
},
{
"name": "李四",
"pid": "500234199299999999",
"mobile": "13098765432",
"applied_at": "1",
"confirmed_at": "",
"confirm_type": "overdue",
"loan_type": 3,
"all": "3"
},
{
"name": "王五",
"pid": "50023415464654659",
"mobile": "1706454894",
"applied_at": "-1",
"confirmed_at": "",
"confirm_type": "overdue",
"loan_type": 3
}
],
"all": "4"
},
"code": 200,
"subtime": "1480495123550",
"status": "success",
"ok": 3
}
FileUtils类是用于读取xx.json文件为字符串的json:
public class FileUtils {
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static String readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
String str = "";
try {
InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(fileName);
reader = new BufferedReader(new InputStreamReader(is));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
str += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return str;
}
}