Java-使用jsonPath根据当前值更新Json

时间:2018-09-21 11:20:33

标签: java jsonpath jayway

我设法使用此代码使用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}]}

有人知道我该如何设法引用旧值吗?
问候

1 个答案:

答案 0 :(得分:1)

您可以使用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 class documentation中进行检查。