有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将一个键放入特定目录中的json中,将该键放入所有目录(JsonPath.parse(String))。放置)

我有一个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并检查(迭代时)是否为父对象。dir1有一些特定的键,例如“goldenKey”。 如果找不到键,则将()放入jsonpath中的“键(goldenKey)” JsonPath。解析(jsonString)。put(jsonpath、键、值)。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中

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


共 (1) 个答案

  1. # 1 楼答案

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