0
我有一個json模板,看起來像這樣。在特定的目錄中放置一個鍵在json中把鍵放在所有目錄(JsonPath.parse(String).put)
{
"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」。 如果沒有找到key,那麼在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 = 「$ .parent.dir1.goldenKey」;' 它實際上是像** giveMeAJsonPathForGivenField(String域)**,所以jsonPaths的方法在其他一些班級中預定義。所以我必須使用該jsonpath值_($。parent.dir1.goldenKey)_來獲取鑰匙(goldenKey)和jsonpath,我必須把它放在_($。parent.dir1)_ 在行 ' jsonpath = jsonpath.substring(0,jsonpath.lastIndexOf(「。」));' jsonpath具有正確的值:「$ .parent.dir1」 – Raghu