杰克逊与jaxb [英] jackson with jaxb
问题描述
在泽西岛使用Jackson JSON
处理器时,何时以及为什么我需要在两者之间使用 JAXB
注释? 对象 - > JAXB-> JSON
when using Jackson JSON
processor in Jersey, when and why would I need to use JAXB
annotations in between? Object->JAXB->JSON
杰克逊还提供了自己的 JAX- RS
提供者直接对象 - > 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:两个}
,而是像 {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使用Jersey / JAXB / Jackson的.util.Map到JSON对象
Also have a look at my question regarding this: Java.util.Map to JSON Object with Jersey / JAXB / Jackson
参考: http://jersey.java.net/nonav/documentation/latest/json.html#d4e894
这篇关于杰克逊与jaxb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!