Ajeet Yadawa
Ajeet Yadawa

Reputation: 163

Jackson JSON: What is the difference between withArray and putArray

While updating the JSON using JACKSON databind, I found two method to add values in "withArray" and "putArray" but I dont found any difference between it. Could someone please clarify the difference between both methods.

 ((ObjectNode)root).withArray("withArray").add("withArray1").add("WithArray2");
 ((ObjectNode)root).putArray("putArray").add("putArray").add("PutArray2");

Sample output: "withArray" : [ "withArray1", "WithArray2" ], "putArray" : [ "putArray", "PutArray2" ]

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.3</version>
</dependency>

Upvotes: 1

Views: 2139

Answers (1)

QuickSilver
QuickSilver

Reputation: 4045

Looks like both method eventually do the same thing which is insert an ArrayNode to the provided node except,

  1. withArray would check if the 'withArray' child exists and is of type ArrayNode . If yes it would return the existing value but putArray would override it.
  2. withArray would throw UnsupportedOperationException if the child node with the withArray exists and is of not type ArrayNode. But putArray would override it anyway.
  3. withArray method would only add the child node if the child is not present.

Upvotes: 5

Related Questions