1

I'm building a complex JSON object with Jackson and I want to structure the code to display the JSON structure clearly, so I'm trying to use the JsonNode API with chained with, put and set methods. At one place inside all this chained stuff I need to add two arrays one after the other. Here's a simplified excerpt:

com.fasterxml.jackson.databind.ObjectNode json = new ObjectNode(JsonNodeFactory.instance);
json.with("data")
    .set("array1", arrayNode1)
    .set("array2", arrayNode1);

I want it to create this JSON:

{
    "data": {
        "array1": [...],
        "array2": [...]
    }
}

First set is fine because it's called on ObjectNode. The problem is it returns JsonNode, which doesn't have a set method, and so the second set call results in compilation error.

How can I chain setting two arrays?

Vytautas
  • 452
  • 3
  • 11

1 Answers1

0

It doesn't really improve readability that much, but if you have Guava on the classpath, you can do the following:

ObjectNode json = new ObjectNode(JsonNodeFactory.instance);
json.with("data")
    .setAll(ImmutableMap.of(
        "array1", arraynode1, 
        "array2", arraynode2));

setAll returns the object node.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
  • Yeah, I guess it's a way to do it, thanks. Although I'm wondering why Jackson restricts JsonNode's API this way. – Vytautas Nov 29 '17 at 11:39
  • It's a flaw in the API where it returns a JsonNode instead of an ObjectNode and thus breaks chaining but this behavior can't be "fixed" directly without breaking backward compatibility: https://stackoverflow.com/questions/37543058/using-jackson-s-objectnode-putobject-for-method-chaining – Khorkrak Jul 18 '20 at 15:16