Vishvesh Phadnis
Vishvesh Phadnis

Reputation: 2588

Dynamically updating JSON document in java

I have different JSON document. I want to update value against specified path. How can I achieve this.

Below is the two sample JSON's

{
  "A": [
    [
      [
        [
          {
            ".": null
          }
        ],
        [
          {
            "M": null
          }
        ]
      ]
    ],
    [
      {
        "A": "Update"
      }
    ]
  ]
}

Suppose I have given path : A[1][0].A for given path I want to change the value update to updated

In case of array I'm using indexes. keys are sepeared by . Note : JSON document structure is not fixed.

Upvotes: 0

Views: 2223

Answers (1)

K139
K139

Reputation: 3669

You can do that using Json Path.

All you need to do is define configuration and use JSON Path structure to edit a particular node.

Configuration config= Configuration.builder()
    .jsonProvider(new JacksonJsonNodeJsonProvider())
    .mappingProvider(new JacksonMappingProvider())
    .build();

JsonNode newJson=JsonPath.using(config).parse(yourActualJSONString).set("$.A[2].A","UPDATED").json();
System.out.println(newJson.toString());

Refer this for JsonPath syntax.

and if you are using Maven to build your project, then here is the dependency

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

(or)

Link to the JSON Path JAR file.

Upvotes: 2

Related Questions