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?