我必须使用一个只提供 JAXBContext 的库来将 XML 数据编码和解码为 Java 对象。我也从未见过 XML:只有 JAXB 对象传递给我。我现在需要的是将这些对象转换为 JSON,而不是 XML。
有没有办法从给定的 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-core
和jackson-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"}
更新
另见 this post .看起来 MOXy 也提供这种支持。
关于java - 从未知的 JAXBContext (XML) 为 JSON 创建编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26063268/