在我的 Jersey 项目中,我使用 MOXy 来编码 JSON。我想要编码(marshal)的类之一是一个可能为空的字符串数组。
class Data
{
@XmlElement(nillable = true) public String[] array;
}
在数组为空的情况下,我希望输出为:
{
"array" : []
}
但是看起来 MOXy 正在从输出中过滤掉空数组。如何让它在输出中包含空数组?
我正在考虑将 JSONConfiguration.mapped().array("array").build() 添加到 MOXy 提供程序构造函数中,但这似乎没有什么区别(而且我什至不确定它是正确的解决方案)。
最佳答案
注意:我是EclipseLink JAXB (MOXy) JAXB 2 (JSR-222) 的领导者和成员专家组。
原始答案
已输入以下增强请求。您可以使用下面的链接来跟踪我们在此问题上的进展。
更新
从 2012 年 5 月 19 日的 EclipseLink 2.4.0 标签开始,您可以设置以下属性来获得您正在寻找的行为。
marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, true);
您可以从以下位置下载夜间 EclipseLink 标签:
根
在下面的类中,我们有三个 List
属性。 List
对象中有两个为空,一个为 null。请注意,emptyChoiceList
字段是使用 @XmlElements
映射的。 @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" : [ ]
}
关于jaxb - MOXy如何处理空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453441/