0

我有一个具有以下示例结构的 json 文件

{
  "contract": {
    "marketScope": "AT",
    "businessPartner": "GBM",
    "salesChannelInformation": {
      "salesChannelCode": "Integrated",
      "salesChannel": "B-Partner information 1"
    }
}

给出一个 jsonpath,我想修改一个特定的键值。

例如,将“contract.salesChannelInformation.salesChannelCode”的值更改为“Integrated-Test”

目前我有以下代码:

public void setProperty(String fileString,String path, String value) {

    if(JsonPath.given(fileString).get(path) == null){
        Assert.fail("Path does not exist on json file");
    }else {

        try {
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(fileString);


            System.out.println(jsonObject);

            String[] tokens = path.split("\\.");
            for (String token : tokens) {
                System.out.println(token);
                // Iterate the JsonObject, reach the key and modify the value

            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
    }


}

我希望以这种方式修改json文件

{
  "contract": {
    "marketScope": "AT",
    "businessPartner": "GBM",
    "salesChannelInformation": {
      "salesChannelCode": "Integrated-Test",
      "salesChannel": "B-Partner information 1"
    }
}
4

1 回答 1

4

com.jayway.jsonpath.DocumentContext.set() 可用于修改 JSON 中元素的值

   /**
     * Set the value a the given path
     *
     * @param path      path to set
     * @param newValue  new value
     * @return a document context
     */
    DocumentContext set(JsonPath path, Object newValue);

图书馆:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version><!--Version--></version>
</dependency>

代码片段:

String json = "{\n" +
                "\t\"contract\": {\n" +
                "\t\t\"marketScope\": \"AT\",\n" +
                "\t\t\"businessPartner\": \"GBM\",\n" +
                "\t\t\"salesChannelInformation\": {\n" +
                "\t\t\t\"salesChannelCode\": \"Integrated\",\n" +
                "\t\t\t\"salesChannel\": \"B-Partner information 1\"\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";
        DocumentContext parsedDataContext = jsonParseContext.parse(json);

        parsedDataContext.set("$..contract.salesChannelInformation.salesChannelCode", "Integrated-Test");

        System.out.println(parsedDataContext.jsonString());

输出:

{"contract":{"marketScope":"AT","businessPartner":"GBM","salesChannelInformation":{"salesChannelCode":"Integrated-Test","salesChannel":"B-Partner information 1"}}}
于 2019-04-09T12:27:10.863 回答