Reputation: 2638
I need to write some appender method that adds "JsonNode" objects together. In the end, this would run recursively over a few hundreds of iterations. Eventually I would convert it to an Avro object. So apart from "just getting it to work" I would also want to keep memory consumption into consideration.
A simplified example below:
val s1 = """{"condition": "yes",
"id": "file",
"value": "File" }"""
val s2 = """{"condition": "no",
"id": "file2",
"value": "File2" }"""
val mapper = new ObjectMapper()
val obj1: JsonNode = mapper.readTree(s1)
val obj2: JsonNode = mapper.readTree(s2)
// the following doesn't work obviously, but that's what I'm trying to do
val result = obj1 + obj2
println(result.toString)
the desired output would be:
[{"condition": "yes",
"id": "file",
"value": "File" },
{"condition": "no",
"id": "file2",
"value": "File2" }]
I've been fiddling around with a few options, but I can't seem to get an easy append to work. Unless of course I go the "string" route, but that's not as clean as I would like it to be. (append s1 and s2 seperated by a ,
and wrap it in []
brackets)
Upvotes: 2
Views: 4194
Reputation: 10127
As @yokomizor already commented, you need to build an ArrayNode
with the two elements obj1
and obj2
:
val result: ArrayNode = mapper.createArrayNode()
result.add(obj1)
result.add(obj2)
or even simpler:
val result: ArrayNode = mapper.createArrayNode().add(obj1).add(obj2)
The additional memory foot-print of this is as small as it can be,
because the internal implementation of ArrayNode
simply has a private List<JsonNode> _children
,
and you have the JsonNode
s already in memory anyway.
Upvotes: 2