JAXB编组列表< String> JSON? [英] JAXB marshall List<String> JSON?
问题描述
我正在使用JAXB(MoXY)来同时以XML和JSON编组/解组我的数据.
I am using JAXB (MoXY) for marshalling/unmarshalling my data in XML and JSON both.
我有一个List<String>
包裹在一个类中,我想通过电线发送它:
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;
}
}
XML符合预期:
<prefix:carList xmlns:prefix="http://www....some prefix namespace...">car1 car2 car3</prefix:carList>
但是我得到的JSON是:
But the JSON I am getting is:
{
"prefix:carList" : "car1 car2 car3"
}
我的JSON marshaller属性:
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);
但是我想要我的JSON:
But I want my JSON like:
{
"prefix:carList" : [ "car1", "car2", "car3" ]
}
我是JAXB的新手.为了使JSON符合需要,我需要进行哪些更改?我愿意修改我的域类CarsList
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
在list元素上添加@XmlList
批注,还添加其键名(cars
),例如:
Adding @XmlList
annotation on the list element, also adds its key-name (cars
) like:
{
"prefix:carsList" : {
"cars" : ["car1", "car2", "car3"]
}
}
这是不希望的.
感谢您的帮助.
推荐答案
我认为此编组设置应该可以解决您的问题:
I think this marshaller setting should solve your issue:
marshaller.setProperty(MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
这篇关于JAXB编组列表< String> JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!