https://github.com/json-path/JsonPath
看网址像是官方的,可以在线测试表达式,还是蛮好使的
http://jsonpath.com/
https://goessner.net/
gradle依赖
// https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.4.0'
操作符
运算符
使用JsonPath修改Json数据
{
"apis":[
{
"ctime":"2018-11-08 16:01:16",
"mtime":"2019-02-20 22:11:42",
"modifierId":1,
"creatorId":1,
"apiId":"1",
"authType":"none",
"version":"v3",
"path": "/test",
"httpMethod":"POST",
"serviceCode":"resource",
"cateCode":"server-task",
"mappingProtocol":"DUBBO",
"modifyVersion":1,
"onlineVersion":1,
"isOnline":"Y",
"isCached":"N",
"cachedTime":10000,
"requestMode":"MAPPING",
"servCreatorId":1134,
"requestMappingParam":{
"requestParams":[
{
"name":"tenantId",
"type":"Long",
"paramLocation":"Query",
"isRequired":true,
"defaultValue":""
},
{
"name":"userId",
"type":"Long",
"paramLocation":"Query",
"isRequired":true,
"defaultValue":""
},
{
"name":"taskId",
"type":"Long",
"paramLocation":"Query",
"isRequired":false,
"description":"ID"
},
{
"name":"taskName",
"type":"String",
"paramLocation":"Query",
"isRequired":true,
"defaultValue":"",
"description":"名称"
}
]
}
"dubboParamMappings": {
"leafParamMappings": [
{
"paramName":"tenantId",
"paramType":"java.lang.Long",
"paramMapping":"tenantId"
}
]
}
}
]
}
apis是个列表,列表包含很多map集合。
每个map代表一个api,api中包含requestParams。
其中需要将requestParams中tenantId和userId参数加上headerMapping。
"requestParams":[
{
"name":"tenantId",
"type":"Long",
"paramLocation":"Query",
"isRequired":true,
"defaultValue":"",
"headerMapping":"X-Access-TenantId" // 需要添加的东西
},
{
"name":"userId",
"type":"Long",
"paramLocation":"Query",
"isRequired":true,
"defaultValue":"",
"headerMapping":"X-Access-UserId" // 需要添加的东西
},
首先,读取json文件:
InputStream inputStream = Files.newInputStream(Paths.get("/Users/admin/Downloads/resource.json"));
构造整个文档
DocumentContext document = JsonPath.parse(inputStream);
在指定位置添加key value
(1)$.apis[*]是获取所有apis,这里其实只有一个。。。
(2)$.apis[*].requestMappingParam是获取apis列表中每个map的requestMappingParam
(3)$.apis[*].requestMappingParam.requestParams是获取上一步requestMappingParam中的requestParams
(4)[?(@.name==“tenantId”&&!@.headerMapping)]这个是过滤条件,指的是requestParams中包含name且等于tenantId并且requestParams没有headerMapping这个key
document.put("$.apis[*].requestMappingParam.requestParams[?(@.name==\"tenantId\"&&!@.headerMapping)]", "headerMapping", "X-Access-TenantId");
document.put("$.apis[*].requestMappingParam.requestParams[?(@.name==\"userId\"&&!@.headerMapping)]", "headerMapping", "X-Access-UserId");
(5)后面两个参数分别是key和value
写入修改后的json
Files.write(Paths.get("/tmp/resource.json")), context.jsonString().getBytes());
动力节点在线课程涵盖零基础入门,高级进阶,在职提升三大主力内容,覆盖Java从入门到就业提升的全体系学习内容。全部Java视频教程免费观看,相关学习资料免费下载!对于火爆技术,每周一定时更新!如果想了解更多相关技术,可以到动力节点在线免费观看JSONPath视频教程哦!
代码小兵64503-29 11:46
代码小兵87208-06 11:36
代码小兵34507-29 13:19