简体   繁体   中英

Jackson List Help - Java

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.

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

Try JAXB Annotations like this:

 @XmlElementWrapper(name = "Messages")
  // XmlElement sets the name of the entities
  @XmlElement(name = "Message")
  public List<Message> messages;

See http://wiki.fasterxml.com/JacksonJAXBAnnotations for using JAXB annotations with Jackson.

There's a good JAXB tutorial here:

http://www.vogella.com/articles/JAXB/article.html

and here:

https://jaxb.java.net/tutorial/index.html

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;

You could also try using:

@JacksonXmlRootElement(localName = "Messages")
class Messages{
    @JacksonXmlProperty(localName = "Message")
    List<String> message = new ArrayList<>();

    public List<String> getMessage() {
        return message;
    }

    public void setMessage(String message) {
       this.message.add(message);
    }
}

As another option you can do it without annotations by changing the XML. You would change the XML to,

<messages>
  <Message>
    <value>"foo"</value>
  </Message>
  <Message>
    <value>"bar"</value>
  </Message>
</messages>

and change the Java to

class Foobar {
  List<Message> messages;
}
class Message {
  String value;
}

Then Messages would contain two objects of the Message class, one where the value member equals "foo" and the other where the value member equals "bar".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM