Using Jackson XML binding to map lists to Pojo

1.6k views Asked by At

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.

1

There are 1 answers

0
EliandroRibeiro On

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).