繁体   English   中英

从未知的JAXBContext(XML)为JSON创建Marshaller

[英]Create Marshaller for JSON from unknown JAXBContext (XML)

我必须使用一个只提供JAXBContext的lib来为XML对象编组和解组XML数据。 我也从未见过XML:只有JAXB对象传递给我。 我现在需要的是将这些对象转换为XML,而不是转换为JSON。

有没有办法从给定的JAXBContext创建一个可用于生成JSON输出的编组器?

情况是我不仅在改造数据。 我还有逻辑,它作用于XML和JSON之间的Java对象(并操纵数据)。 这也是双向转型。 JAXBContext是关于XML和Java对象之间转换的信息 - 我的目的是重用这个上下文信息,而不必使用与JAXB不同的第二种技术实现第二次转换。 JAXBContext(及其Java对象)已经拥有有关XML结构的信息; JAXB自动识别该结构是使用它的省时省力的原因。

如果您的JAXB类只使用基本注释,您可以查看JacksonJAXBAnnotations ,允许Jackson映射器识别JAXN注释。 四行代码(在最简单的编组案例中)就是你所需要的。

ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module);
mapper.writeValue(System.out, yourJaxbObject);

您可以在上面看到所有支持的注释的链接。 你需要的maven神器是

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>2.4.0</version>
</dependency>
  • 请参阅github获取jackson-module-jaxb-annotations - 请注意,此工件依赖于jackson-corejackson-databind 因此,如果您不使用maven,那么您还需要确保下载这些工件

简单的例子:

JAXB类

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "hello",
    "world"
})
@XmlRootElement(name = "root")
public class Root {

    @XmlElement(required = true)
    protected String hello;
    @XmlElement(required = true)
    protected String world;

    // Getters and Setters
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <hello>JAXB</hello>
    <world>Jackson</world>
</root>

测试

public class TestJaxbJackson {
    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Root.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        InputStream is = TestJaxbJackson.class.getResourceAsStream("test.xml");
        Root root = (Root)unmarshaller.unmarshal(is);
        System.out.println(root.getHello() + " " + root.getWorld());

        ObjectMapper mapper = new ObjectMapper();
        JaxbAnnotationModule module = new JaxbAnnotationModule();
        mapper.registerModule(module);
        mapper.writeValue(System.out, root);
    }
}

结果

{"hello":"JAXB","world":"Jackson"}

更新

另见这篇文章 看起来MOXy也提供这种支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM