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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With