使用 Jettison 的多维数组

Multidimensional arrays with Jettison

我正在使用 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 开箱即用地以这种方式序列化。

深入研究 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));
    }
}