修改具有jsonpath的Json

时间:2019-04-09 12:11:31

标签: java json

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

1 个答案:

答案 0 :(得分:2)

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

const amqplib = require('amqplib');

class IRabbitMQ {

    constructor() { }

    async init(host) {
        try {
            const connection = await amqplib.connect(host);
            const channel = await connection.createChannel();
            channel.prefetch(1);
            console.log(' [x] Awaiting RPC requests');
            this.connection = connection;
            this.channel = channel;
        }catch(err) {
            console.error(err);
        }
    }

    log() {
        console.log(this.connection);
    }
}

async function createInstance(){
    const instance = new IRabbitMQ();
    try {
        await instance.init('amqp://localhost');
    }catch (e) {
        throw new Error('OOPS!');
    }
    return instance;
}

async function runLogic() {
    const r = await createInstance();
    r.log();
}

runLogic().catch(console.log);

图书馆:

   /**
     * 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());