slartidan :
I want to serialize an array of POJOs into a custom XML-Format, in my spring boot application using Jackson. The node name child
will be modified at runtime.
I already manage to create a root with one child like this:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
class MyPojo {
public int random = new Random().nextInt();
public static void main(String[] args) throws JsonProcessingException {
List<MyPojo> list = Arrays.asList(new MyPojo(), new MyPojo());
XmlMapper mapper = new XmlMapper();
final ObjectWriter writer = mapper.writer().withRootName("parent");
ObjectNode node = mapper.createObjectNode();
list.forEach(x -> node.putPOJO("child", x)); // <= does not work, replaces values instead of adding them
String s = writer.writeValueAsString(node);
System.out.println(s);
}
}
I want it to output:
<parent>
<child>
<random>123</random>
</child>
<child>
<random>234</random>
</child>
</parent>
But the current code only outputs:
<parent>
<child>
<random>234</random>
</child>
</parent>
How can I add several children and still keep my own node names?
Sharon Ben Asher :
You need to put an ArrayNode
and add the children to it
OjectNode node = mapper.createObjectNode();
ArrayNode arrayNode = node.putArray("child");
list.forEach(x -> arrayNode.addPOJO(x));