简体   繁体   中英

Using Jackson XML binding to map lists to Pojo

I am using Jackson's XML binding to convert XML into a Java List, via an initial mapping to a Java POJO. What I have written works but I don't think I am using Jackson correctly.

I am stuck with this ugly XML:

<groups>
  <groups>One</groups>
  <groups>Two</groups>
  <groups>Three</groups>
</groups>

Here is the Java POJO I am using. Note the setGroups(String) method is actually adding to the list.

public class Groups {
   private List<String> groups = new ArrayList<String>();

   public void setGroups(String group) {
      groups.add(group);
   }

   public List<String> getGroups() { 
      return this.groups;
   }
}

Here is how I invoke Jackson's XmlMapper.

public List<String> getListOfGroups(String xmlDoc) {
   XmlMapper mapper = new XmlMapper();
   Groups groups = mapper.readValue(xmlDoc, Groups.class);
   return groups.getGroups();
}

This is actually working as I need it to work. I get a Groups class with a list populated with the elements I expect. I am wondering, is approach is correct? I don't like that I have a setter doing an add but everything I've tried has not worked.

Your POJO could be simple like this:

public class Groups {
    private List<String> groups;

    public List<String> getGroups() { 
        return this.groups;
    }
}

It will work fine since you use the MapperFeature.USE_GETTERS_AS_SETTERS (enabled by default).

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