我正在使用Jaxb和Jettison(最初是Resteasy)将对象序列化为json。我要序列化的对象之一包括一个二维数组。如何配置Jettison以在json中生成多维数组?
下面是生成多维数组的示例:
public class Example {
@XmlRootElement("test")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Tester {
int[][] stuff;
}
public static void main(String[] args) throws JAXBException {
Tester tester = new Tester();
tester.stuff = new int[][]{{1, 2}, {3, 4}};
StringWriter writer = new StringWriter();
Configuration config = new Configuration();
MappedNamespaceConvention con = new MappedNamespaceConvention(config);
MappedXMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(con, writer);
Marshaller marshaller = JAXBContext.newInstance(Tester.class)
.createMarshaller();
marshaller.marshal(tester, xmlStreamWriter);
System.out.println(writer.toString());
}
}
输出以下内容:
{"tester":{"stuff":[{"item":[1,2]},{"item":[3,4]}]}}
但是,我想将stuff
数组输出为多维json数组,如下所示:
{"tester":{"stuff":[[1,2],[3,4]]}}
这似乎是可能的,因为Resteasy可以立即使用这种方式进行序列化。
答案 0 :(得分:0)
在对Resteasy进行深入研究后,发现在Jboss中使用默认json提供程序时会使用Jackson。作为参考,此代码提供了所需的结果:
public class Example {
@XmlRootElement("test")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Tester {
int[][] stuff;
}
public static void main(String[] args) throws JAXBException {
Tester tester = new Tester();
tester.stuff = new int[][]{{1, 2}, {3, 4}};
StringWriter writer = new StringWriter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JaxbAnnotationModule());
System.out.println(objectMapper.writeValueAsString(tester));
}
}