gpt4 book ai didi

java - 修改具有 jsonpath 的 Json

转载 作者:行者123 更新时间:2023-12-02 01:33:38 25 4
gpt4 key购买 nike

我有一个具有以下示例结构的 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"
}
}

最佳答案

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"}}}

关于java - 修改具有 jsonpath 的 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com