[英]Java - use jsonPath to update Json based on current value
我设法使用带有此代码的 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 类文档中检查它。
您可以使用 JsonPath 的解析和设置功能。
例子:
public static String replaceOldValueVithNewValueforGivenPath(String jsonBody, String path, String newValue)
{
// validateJsonInput(jsonBody);
try {
return JsonPath.parse(jsonBody).set(path,newValue).jsonString();
} catch (PathNotFoundException var3) {
throw new RuntimeException("No results for path: " + path);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.