杰克逊与 jaxb [英] jackson with jaxb

查看:39
本文介绍了杰克逊与 jaxb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Jersey 中使用 Jackson JSON 处理器时,我何时以及为什么需要在两者之间使用 JAXB 注释?Object->JAXB->JSON

when using Jackson JSON processor in Jersey, when and why would I need to use JAXB annotations in between? Object->JAXB->JSON

Jackson 还提供了它自己的 JAX-RS 提供程序以直接使用 Object->JSON.这种方法缺少什么?或者为什么我更喜欢另一个

Jackson also provides it's own JAX-RS provider to go direct Object->JSON. what is missing in this approach? or why would I prefer on over another

ps:我也用弹簧

推荐答案

要生成 JSON,您通常只需要指定 @Produces(MediaType.APPLICATION_JSON).然而,这将默认采用 JAXB 路由.

For generating JSON you generally just have to specifiy @Produces(MediaType.APPLICATION_JSON). This will however take the JAXB route by default.

使用 Object -> JAXB -> JSON,您必须使用 @XmlRootElement 注释要映射的类.这会工作得很好,但是一旦你开始序列化一个 HashMap,你最终不会得到一个明显的 {keyOne:"one",keyTwo:"two"} 而是一些奇怪的东西,比如 {entry:[{key:"keyOne",value:"one"},{key:"keyTwo",value:"two"}]}.

With Object -> JAXB -> JSON you will have to annotate the classes you want to map with @XmlRootElement. This will work fine, but once you get to serializing a HashMap you will not end up with an obvious {keyOne:"one",keyTwo:"two"} but rather something strange like {entry:[{key:"keyOne",value:"one"},{key:"keyTwo",value:"two"}]}.

所以要采用直接的 Object -> JSON 方式,只需在 web.xml 中指定以下内容:

So to take the direct Object -> JSON way, just specify the following in your web.xml:

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

使用此 JSON 映射将按照您期望的方式工作.只是不要忘记删除 @XmlRootElement 注释,它们会在 POJO 映射打开时强制生成 XML.

With this JSON mapping will work just the way you would expect it to work. Just don't forget to remove the @XmlRootElement annotations, they force XML generation when POJO mapping is turned on.

另外看看我的问题:Java.util.Map to JSON Object with Jersey/JAXB/Jackson

参考:http://jersey.java.net/nonav/documentation/latest/json.html#d4e894

这篇关于杰克逊与 jaxb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆