Will
Will

Reputation: 3585

Java: Can I use JAXB to serialize a list of strings?

I have nothing more complex than a list of strings. I have implemented several methods to make simpler use of JAXB to serialize various classes.

The List exists inside no other classes, it's just a simple List that I need to load into a ComboBox at run time, and allow the user to save/load the contents of at their leisure.

Is it possible for me to use JAXB to serialize a List object, and if so, how?

Upvotes: 3

Views: 3938

Answers (2)

icza
icza

Reputation: 417662

It is possible, but it will be less efficient than a simple wrapper class with a List field.

Following your comments on @BlaiseDoughan's answer, here is your SaveableList implementation. Basically what you need is a class which implements List and forwards all calls to an internal List implementation, e.g. ArrayList. In my example I extend AbstractList for simplicity.

SaveableList implementation:

class SaveableList extends AbstractList<String> {

    @XmlElement(name="e")
    private final List<String> list = new ArrayList<>();

    @Override
    public String get(int index) {
        return list.get(index);
    }

    @Override
    public boolean add(String e) {
        return list.add(e);
    }

    @Override
    public int size() {
        return list.size();
    }

    // You might want to implement/override other methods which you use
    // And is not provided by AbstractList

}

Example usage:

List<String> list = new SaveableList();
list.add("one");
list.add("two");

// Save it to XML
JAXB.marshal(list, new File("list.xml"));

// Load it from XML:
List<String> list2 = JAXB.unmarshal(new File("list.xml"), SaveableList.class);

Here is the XML it generates:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<saveableList>
    <e>one</e>
    <e>two</e>
</saveableList>

Upvotes: 2

bdoughan
bdoughan

Reputation: 149017

JAXB requires the object you are marshalling to be a domain object. Therefore you would need to introduce a wrapper like the following to do the marshalling.

 @XmlRootElement(name="strings)
 public class ListOfStrings {

     private List<String> strings;

     @XmlElement(name="string")
     public List<String> getStrings() {
         return strings;
     }

     public void setStrings(List<String> strings) {
         this.strings = strings;
     }

 }

Upvotes: 0

Related Questions