How to add data in existing json object in java using Jsonpath

401 views Asked by At

below is json string :

 {
  "Data1": "",
  "Data2": {
    "id": 1234
  },
  "Data3": [
    {
      "id": "id2",
      "price": [
        {
          "id": "id3"
        }
      ],
      "account": {
        "id": "%s"
      },
      "product": {
        "extension": {
          "sub": "R"
        }
      },
      "reason": [
        {
          "extension": {}
        }
      ],
      "produracteristic": [
        {
          "name": "gt",
          "value": "none"
        }
      ],
      "extension": {

       }
    }
  ],

 "Data4":[
    ....
  }
}

I want to add data under json payload.Data3.extension want to add date:28-08-2023, so it will be ,

  "extension": {
 date:28-08-2023
        }

I have tried using java but that was only working for add element in json array. but in my case I am not adding in array . I am adding it to an object under array. Please help me on this

JsonPath pathToArray = JsonPath.compile("$.data3.extension");
documentContext.add(pathToArray, Collections.singletonMap("date", "28-08-2023"));
1

There are 1 answers

3
ash On

I have use the dependency named Fastjson, and found it easy to implementd it.
Follow is my code.

    public static void main(String[] args) {
//1.generate the json string from a object by fastjson
            String s = JSON.toJSONString(new Person());
            System.out.println("s = " + s);
//2.fastjson transfer the jsonStr to a JSONObject
            JSONObject jsonObject = JSONObject.parseObject(s);
//3. use the JSONObject to add a field named field1 and the value is 111
            JSONObject address = jsonObject.getJSONObject("address");
            address.put("field1", 111);

            System.out.println("jsonObject = " + jsonObject);

        }

The output is:

s = {"address":{"city":"2","province":"1"},"age":18,"gender":"man","name":"zhangsan"}
jsonObject = {"address":{"field1":111,"province":"1","city":"2"},"gender":"man","name":"zhangsan","age":18}

If you want to use this ,you can add this in your maven files.

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>2.0.32</version>
</dependency>