使用JACKSON将JAXB转换为JSON

6

我的应用程序中,JAXB输出的格式如下:

this.marshalOut(jaxb_Object, fileOutputStream);

这是调用Spring对象XML映射马歇尔生成XML文件的方法。现在,我也想在此行之后生成JSON文件。有人知道如何使用JAXB输入生成JSON输出吗?

我在网上找到了这个示例代码:

ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
// make deserializer use JAXB annotations (only)
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
// make serializer use JAXB annotations (only)
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
mapper.writeValue( outputStream, jaxb_object);

setAnnotationIntrospector已经被弃用,是否有其他解决方法?


你可能会对我们在EclipseLink JAXB (MOXy)中添加的对象到JSON支持感兴趣:http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html - bdoughan
我需要使用任何与Jackson相关的东西,因为我们的项目中正在使用Jackson。 - user1417746
你看过Spring的MappingJacksonHttpMessageConverter吗?如果你没有使用HttpMessageConverters,这个源代码至少可以给你一些提示。 - MattR
5个回答

8
以下内容可行(且不使用任何已弃用的构造函数):
ObjectMapper mapper = new ObjectMapper();

AnnotationIntrospector introspector =
    new JaxbAnnotationIntrospector(mapper.getTypeFactory());   

mapper.setAnnotationIntrospector(introspector);

具体来说,这行代码

new JaxbAnnotationIntrospector(mapper.getTypeFactory());

使用了一个未被弃用的构造函数。我已经测试过它可以成功处理JAXB注释(例如我的情况中的@XmlTransient)。


JaxbAnnotationIntrospector.java 可在 jackson-module-jaxb-annotations-2.6.2.jar 中找到。 - Arun Chandrasekaran
@Michael Christoff 太棒了!这在我的情况下也起作用了。非常感谢你。 - Evil Toad

4
您可以使用 jackson-module-jaxb-annotations,如文档所述,您可以注册一个 JaxbAnnotationModule 模块:
JaxbAnnotationModule module = new JaxbAnnotationModule();
// configure as necessary
objectMapper.registerModule(module);

这样做,你现在可以同时使用JAXB注解和Jackson原生注解。

2

对我来说正确的解决方案是:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());


0
根据Jackson javadoc文档:
setAnnotationIntrospector

@Deprecated
public final void setAnnotationIntrospector(AnnotationIntrospector ai)

    Deprecated. Since 1.8, use either withAnnotationIntrospector(AnnotationIntrospector) or Module API instead

    Method for replacing existing annotation introspector(s) with specified introspector. Since this method modifies state of configuration object directly, its use is not recommended

你有没有检查过方法withAnnotationIntrospector(AnnotationIntrospector ai),看看它是否在你的情况下有用?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接