使用Jettison的多维数组

问题描述 投票:0回答:1

我正在使用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开箱即用。

java arrays json jaxb jettison
1个回答
0
投票

在使用Jboss中的默认json提供程序时,在使用Jackson时使用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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.