I am trying to create some xml with Jackson and I cannot get the list to display like I need. I am getting:
<Messages>
<Messages>...</Messages>
<Messages>...</Messages>
</Messages>
I want it to look like:
<Messages>
<Message>...</Message>
<Message>...</Message>
</Messages>
My code looks like this:
public List<Message> messages;
Whatever I name that variable, is the same name all of the child elements get. I am sure this has been answered elsewhere, but I cannot find anything that will take care of my issue. Thanks for the help.
Jackson is one such Java Json library used for parsing and generating Json files. It has built in Object Mapper class which parses json files and deserializes it to custom java objects. It helps in generating json from java objects.
This short tutorial shows how the Jackson library can be used to serialize Java object to XML and deserialize them back to objects.
The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.
Follow mentioned steps, Right click on your project --> Properties --> Java Build Path --> Libraries --> Add External Jar --> Choose jackson-core-2.8. 7. jar which you've recently downloaded and that's it.
I found the easy way to do this without adding more dependencies. You just use the annotations:
@JacksonXmlElementWrapper(localName = "Messages")
@JacksonXmlProperty(localName = "Message")
This question is what pointed me in the right direction. Jackson XML globally set element name for container types. You can also read about this annotation on the github page here
This works perfectly fine for List of Strings.
<Messages>
<Message>msg1</Message>
<Message>msg2</Message>
<Message>msg3</Message>
</Messages>
@JacksonXmlElementWrapper(localName = "Messages")
@JacksonXmlProperty(localName = "Message")
public List<String> messages;
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