Can JAXB output an ArrayList as comma separated values?

前端 未结 3 1067
臣服心动
臣服心动 2021-01-19 07:56

I have something like

@XmlElementWrapper(name=\"Mylist\")
List myItems = new ArrayList()

and that comes out lik

相关标签:
3条回答
  • 2021-01-19 08:19

    you can accomplish that by making the field transient @XmlTransient and creating a method for calculating a String with a comma-separated.

    @XmlTransient
    List<Items> myItems = new ArrayList<Items>()
    
    @XmlElement(name = "myItems")
    public String getItemsAsCommasSeparated() {
        return String.join(", ", myItems);
    }
    

    About the wrapping <Mylist> if it is really necessary you will have to wrap the list into a another object.

    0 讨论(0)
  • 2021-01-19 08:30

    Here's an XmlAdapter to handle comma separated lists:

    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class CommaSeparatedListAdapter extends XmlAdapter<String, List<String>> {
    
        @Override
        public List<String> unmarshal(final String string) {
            final List<String> strings = new ArrayList<String>();
    
            for (final String s : string.split(",")) {
                final String trimmed = s.trim();
    
                if (trimmed.length() > 0) {
                    strings.add(trimmed);
                }
            }
    
            return strings;
        }
    
        @Override
        public String marshal(final List<String> strings) {
            final StringBuilder sb = new StringBuilder();
    
            for (final String string : strings) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
    
                sb.append(string);
            }
    
            return sb.toString();
        }
    }
    

    You would use it like this:

    @XmlElementWrapper(name="Mylist")
    @XmlJavaTypeAdapter(CommaSeparatedListAdapter.class)
    List<Items> myItems = new ArrayList<Items>()
    
    0 讨论(0)
  • 2021-01-19 08:34

    You can use @XmlList to make it a space separated value.

    For a comma separated list you will need to use an XmlAdapter. For more information on XmlAdapter see:

    • http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
    0 讨论(0)
提交回复
热议问题