Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can JAXB output an ArrayList as comma separated values?

I have something like

@XmlElementWrapper(name="Mylist")
List<Items> myItems = new ArrayList<Items>()

and that comes out like

<Mylist>
   <myItems>item 1</myItems>
   <myItems>item 2</myItems>
   <myItems>item 3</myItems>
</Mylist>

Is it possible to make this come out more like

<Mylist>
   <myItems>item 1, item 2, item 3</myItems>
</Mylist>

Since the data I am after is all just textual anyway?

like image 813
Derek Avatar asked Feb 27 '23 01:02

Derek


2 Answers

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
like image 182
bdoughan Avatar answered Mar 03 '23 22:03

bdoughan


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>()
like image 31
idontevenseethecode Avatar answered Mar 03 '23 23:03

idontevenseethecode