简体   繁体   中英

JAXB marshall List<String> JSON?

I am using JAXB (MoXY) for marshalling/unmarshalling my data in XML and JSON both.

I have a List<String> wrapped in a class which I want send over the wire:

@XmlRootElement(name = "carList")
public class CarsList {

    @XmlValue
    protected List<String> cars;

    public List<String> getCars() {
        if (cars == null) {
            cars = new ArrayList<String>();
        }
        return cars;
    }

    public void addCar(String carId) {
        if (cars == null) {
            cars = new ArrayList<String>();
        }
        if (carId != null) {
            this.cars.add(car);
        }
    }

    public void setCars(List<String> cars) {
        this.cars = cars;
    }
}

The XML is coming as expected:

<prefix:carList xmlns:prefix="http://www....some prefix namespace...">car1 car2 car3</prefix:carList>

But the JSON I am getting is:

{
   "prefix:carList" :  "car1 car2 car3"
}

My JSON marshaller properties:

marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false);

But I want my JSON like:

{
   "prefix:carList" : [ "car1", "car2", "car3" ]
}

I am new to JAXB. What changes do I need to make my JSON as desired ?? I am open to modifying my domain class CarsList

Adding @XmlList annotation on the list element, also adds its key-name ( cars ) like:

{
"prefix:carsList" : {
      "cars" : ["car1", "car2", "car3"]
}
}

which is not desired.

Any help is appreciated.

我认为此编组设置应该可以解决您的问题:

marshaller.setProperty(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM