首页 > 解决方案 > 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}]}

有人知道我如何设法引用这样的旧值吗?
问候,

标签: javajsonpathjayway

解决方案


您可以使用 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 类文档中检查它。


推荐阅读