java - Java - 使用 jsonPath 根据当前值更新 Json
问题描述
我设法使用带有此代码的 jsonPath 更新 json 对象
JSONObject json = new JSONObject("{\"data\":[{\"city\":\"New York\",\"name\":\"John\",\"age\":31},{\"city\":\"Paris\",\"name\":\"Jack\",\"age\":12}]}");
DocumentContext doc = JsonPath.parse(json.toString())
.set("$..name","newName");
System.out.println("doc.jsonString() = " + doc.jsonString());
输出:
doc.jsonString() = {"data":[{"city":"New York","name":"newName","age":31},{"city":"Paris","name":"newName","age":12}]}
现在我想根据旧值更新值(通过对旧值应用函数)
类似于
DocumentContext doc = JsonPath.parse(json.toString())
.set("$..name",upper(oldValue))
.set("$..age", oldValue+10);
这将导致以下json
doc.jsonString() = doc.jsonString() = {"data":[{"city":"New York","name":"JOHN","age":41},{"city":"Paris","name":"JACK","age":22}]}
有人知道我如何设法引用这样的旧值吗?
问候,
解决方案
您可以使用 DocumentContext 类的 map 函数,如下例所示:
DocumentContext json = JsonPath.using(configuration).parse(jsonStr);
DocumentContext result = json.map("$..name", (currentValue, configuration) -> {
return currentValue.toString().toUpperCase();
});
System.out.println(result.jsonString());
该示例将值更改为大写。
尝试在Jsonpath DocumentContext 类文档中检查它。
推荐阅读
- c# - 从零四舍五入
- r - 如何在 R 中对序数数据集进行层次聚类?
- java - 如何使用 `java.text.Format` 为我的对象构建自定义格式化程序?
- javascript - Javascript扩展继承
- c# - Xamarin 帐户未激活
- javascript - Html 表单验证标签放置
- javascript - TypeError:无法使用 Ionic 2 读取 HTML5 Canvas 中未定义的属性“nativeElement”
- vba - Microsoft Excel:多次重复特定操作的宏
- xml - 为每个解析xml文件
- gitlab-ci - 推送构建的图像时,Gitlab-runner 有“访问被拒绝”