将 JSON 中的密钥放在特定目录中 将密钥放在所有目录中(JsonPath.parse(String).put)



我有一个看起来像这样的json模板。

{
"parent": {
"dir1": {
"key11": {
"min": 1,
"max": 100
},
"key12": {
"sample1": "txt",
"sample2": "100.25"
}
},
"dir2": {
"key21": {
"min": 1,
"max": 100
},
"key22": {
"sample1": "USD",
"sample2": "100.25"
}
}
}
}

在这里,我有一个逻辑来解析 json 并检查(在迭代时)parent.dir1 是否有一些特定的键,例如"goldenKey"。 如果未找到键,则在 jsonpath 中放置 "key (goldenKey)" JsonPath.parse(jsonString).put(jsonpath, key, value).json();

为了获取放置键的 jsonPath,我将通过将当前 jsonPath 拆分为"."来返回一个节点,并将其转换为需要放置的键。 像下面的代码

try {
//set jsonpath, if key not found then catch
JsonPath.parse(json).set("$.parent.dir1.goldenKey", "golden").json();
} catch (final PathNotFoundException e) {
//json path of the key
String jsonpath = "$.parent.dir1.goldenKey";
//get the key by getting last index of "."
final String key = jsonpath.substring(jsonpath.lastIndexOf(".") +1);
jsonpath = jsonpath.substring(0, jsonpath.lastIndexOf("."));
JsonPath.parse(json).put(jsonpath, "goldenKey", "golden").json();}

问题是,它不是将键值放在给定的 json 路径上(即此代码中的 dir1),而是将键和值放在 dir1 和 dir23 中

如果解释不清楚,请告诉我。

您正在从硬编码的 jsonpath 获取子字符串。 在添加值"goldenKey":"golden"时,应$.parent.dir1jsonpath。这应该仅在 dir1 下添加键值对。仔细检查一次。

最新更新