Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson List Help - Java

Tags:

java

xml

jackson

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.

like image 794
jhamm Avatar asked Jun 12 '13 20:06

jhamm


People also ask

What does Jackson do in Java?

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.

Does Jackson use Java serialization?

This short tutorial shows how the Jackson library can be used to serialize Java object to XML and deserialize them back to objects.

How does ObjectMapper readValue work?

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.

How do I add Jackson to Java?

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.


2 Answers

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

like image 97
jhamm Avatar answered Oct 12 '22 04:10

jhamm


This works perfectly fine for List of Strings.

XML

<Messages>
     <Message>msg1</Message>
     <Message>msg2</Message>
     <Message>msg3</Message>
</Messages>

Jackson Code

@JacksonXmlElementWrapper(localName = "Messages")
@JacksonXmlProperty(localName = "Message")
public List<String> messages;
like image 42
ifelse.codes Avatar answered Oct 12 '22 06:10

ifelse.codes