在我的Jersey项目中,我使用MOXy对JSON进行编组。我想封送的一个类是一个可以为空的字符串数组。
class Data
{
@XmlElement(nillable = true) public String[] array;
}在数组为空的情况下,我希望输出为:
{
"array" : []
}但是,看起来MOXy正在从输出中过滤掉空数组。如何让它在输出中包含空数组?
我正在考虑将JSONConfiguration.mapped().array("array").build()添加到MOXy提供程序构造函数中,但这似乎没有什么不同(我甚至不确定这是不是正确的解决方案)。
发布于 2012-05-09 03:33:59
注意:我是的负责人,也是专家组的成员。
原始答案
已输入以下增强请求。您可以使用下面的链接来跟踪我们在此问题上的进展。
更新
从2012年5月19日的EclipseLink 2.4.0标签开始,您可以设置以下属性来获取您正在寻找的行为。
marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, true);您可以从以下位置下载夜间EclipseLink标签:
根
在下面的类中,我们有三个List属性。其中两个List对象为空,一个为null。请注意,使用@XmlElements映射了emptyChoiceList字段。@XmlElements注释指出可能的节点名是foo和bar。
package forum10453441;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"nullList", "emptyList", "emptyChoiceList"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
private List<String> nullList = null;
private List<String> emptyList = new ArrayList<String>();
@XmlElements({
@XmlElement(name="foo", type=String.class),
@XmlElement(name="bar", type=String.class)
})
private List<String> emptyChoiceList = new ArrayList<String>();
}演示
下面的代码演示如何指定MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS属性。
package forum10453441;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, true);
Root root = new Root();
marshaller.marshal(root, System.out);
}
}输出
现在,在输出中,空列表被编组为空数组。对于使用@XmlElememts映射的字段,在JSON表示中使用指定的节点名。
{
"emptyList" : [ ],
"foo" : [ ]
}https://stackoverflow.com/questions/10453441
复制相似问题