我有一個要求,我需要更新 JSON 中的值。我需要更新的密鑰的路徑也基于某些條件,所以我必須在屬性文件中維護路徑。這是我的 JSONString jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"District1\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";現在我的要求是假設我需要將 pre_paid 的值更新為 N 但需要動態的 pre_paid 的路徑,因為有時我可能需要更新 state_code 或 sort_code 或 pre_paid 等。所以我使用了 JSONPath:String jsonPathExpressionForDistrict = "$['delivery_codes'][0]['postal_code']['district']";String jsonPathExpressionForState_code = "$['delivery_codes'][0]['postal_code']['state_code']";這些路徑我需要存儲在一些屬性文件/數據庫中。我可以通過以下代碼讀取該屬性:JsonPath.parse(jsonString).read(jsonPathExpressionForDistrict , JsonNode.class) -> This gives me value 'District1'但是當我嘗試使用以下代碼更新值時:JsonPath.parse(jsonString).put(jsonPathExpressionForDistrict , "District2", String.class);這給了我以下錯誤:線程“main”com.jayway.jsonpath.InvalidModificationException 中的異常:只能在 com.jayway.jsonpath.internal.PathRef$ObjectPropertyPathRef.put(PathRef.java:265) 的地圖中添加屬性到 com.jayway.jsonpath.JsonPath .put(JsonPath.java:304) at com.jayway.jsonpath.internal.JsonContext.put(JsonContext.java:221) at com.jayway.jsonpath.internal.JsonContext.put(JsonContext.java:199) at com。 .service.ServiceImpl.main(ServiceImpl.java:179)有人請指導我。
3 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
我知道為時已晚,但也許這可以幫助其他人。OP 收到該錯誤,因為 valuejsonPathExpressionForDistrict
是屬性的路徑,而不是 JSON 對象或地圖。
要添加district2
到postal_code
,路徑應該是"$['delivery_codes'][0]['postal_code']"
。
要使用 JSonPath 更新/添加 JSON 中的任何值,我們可以使用帖子中提到的方式,但需要檢查并確保源 JSON 對象中的路徑有效。
添加回答
舉報
0/150
提交
取消