Domanda

Does XStream have support for xml lists similar to JAXB?(https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/XmlList.html)

For example:

 @XmlRootElement
 public class MyClass {
     @XmlElement
     @XmlList
     List<Integer> values;
     //+ getter & setters
 }

generates:

 <myClass>
   <values>1 2 3 4 5</values>
 </myClass>

I am not able to locate any converter that does this. In fact, there seems to be a converter com.thoughtworks.xstream.converters.collections.BitSetConverter that serializes BitSet as comma separated list.

È stato utile?

Soluzione

You can create a custom SingleValueConverter to convert the list:

public class IntegerListConverter implements SingleValueConverter {
    @Override
    public boolean canConvert(Class clazz) {
        return List.class.isAssignableFrom(clazz);
    }

    @Override
    public Object fromString(String arg0) {
        Collection<Integer> collection = new ArrayList<Integer>();
        String[] integerStrings = arg0.split(" ");
        for (int i = 0; i < integerStrings.length; i++) {
            collection.add(Integer.valueOf(integerStrings[i]));
        }
        return collection;
    }

    @Override
    public String toString(Object arg0) {
        List collection = (List) arg0;
        StringBuffer sb = new StringBuffer();
        boolean first = true;
        for (Object object : collection) {
            if (first) {
                first = false;
            } else {
                sb.append(' ');
            }
            sb.append(object.toString());
        }
        return sb.toString();
    }
}

The fact that List<Integer> is a generic interface makes things a little complicated. This implementation of canConvert will give false positives for Lists that contain other things than Integers. I'm not sure if the clazz parameter contains enough information to determine the generic type arguments. So the safest probably is to assign the converter to that single field only:

public class MyClass {
     @XStreamConverter(IntegerListConverter.class)
     List<Integer> values;
     //+ getter & setters
}

Also, this implementation of fromString will always generate an ArrayList, but that ought to be fine I suspect.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top