【问题标题】:Multidimensional arrays with Jettison使用 Jettison 的多维数组
【发布时间】:2018-10-17 00:36:45
【问题描述】:

我正在使用 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】:

    在对 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));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      相关资源
      最近更新 更多