Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jackson’s ObjectNode.putObject for method chaining

Tags:

java

jackson

I have this code:

static String createRequestJson(String apiKey, String apiSecret) {
  JsonNodeFactory factory = JsonNodeFactory.instance;
  ObjectNode root = factory.objectNode();
  root.set("auth", factory.objectNode()
      .put("api_key", apiKey)
      .put("api_secret", apiSecret));
  root.put("wait", true);
  return root.toString();
}

It works, but the code looks more complicated than necessary. In particular, I’d like to get rid of the root variable.

static String createRequestJson(String apiKey, String apiSecret) {
  JsonNodeFactory factory = JsonNodeFactory.instance;
  return factory.objectNode()
      .set("auth", factory.objectNode()
          .put("api_key", apiKey)
          .put("api_secret", apiSecret))
      .put("wait", true) // Compile error: JsonNode.put(String, boolean) undefined
      .toString();
}

The problem is that the set method does not return an ObjectNode but only a JsonNode, which breaks the method chaining.

Did I overlook something obvious, or is it not possible to create such nested objects in one go?

like image 975
Roland Illig Avatar asked May 31 '16 10:05

Roland Illig


1 Answers

This is an unfortunate flaw in method signature, but unfortunately one that is not possible to change without breakage for existing code: if signature was changed (return type is part of signature), any existing code using this method would fail to load with newer versions of Jackson.

So, yes, it is a bug of sorts, but unfortunately one that is very difficult to fix.

like image 195
StaxMan Avatar answered Nov 03 '22 02:11

StaxMan