java 杰克逊与 jaxb
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6001817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson with jaxb
提问by Spring
when using Hymanson JSON
processor in Jersey, when and why would I need to use JAXB
annotations in between? Object->JAXB->JSON
JSON
在 Jersey 中使用 Hymanson处理器时,我何时以及为什么需要JAXB
在两者之间使用注释?Object->JAXB->JSON
Hymanson 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
Hymanson 还提供了自己的JAX-RS
provider 来直接访问Object->JSON
。这种方法缺少什么?或者为什么我更喜欢另一个
ps: I use also spring
ps:我也用弹簧
回答by samy-delux
For generating JSON you generally just have to specifiy @Produces(MediaType.APPLICATION_JSON)
. This will however take the JAXB route by default.
要生成 JSON,您通常只需要指定@Produces(MediaType.APPLICATION_JSON)
. 然而,这将默认采用 JAXB 路由。
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 -> JAXB -> JSON,您必须注释要映射的类@XmlRootElement
。这会工作得很好,但是一旦你开始序列化 aHashMap
你最终不会得到一个明显的{keyOne:"one",keyTwo:"two"}
而是像{entry:[{key:"keyOne",value:"one"},{key:"keyTwo",value:"two"}]}
.
So to take the direct Object -> JSON way, just specify the following in your web.xml:
因此,要采用直接 Object -> JSON 方式,只需在 web.xml 中指定以下内容:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
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.
使用此 JSON 映射将按照您期望的方式工作。只是不要忘记删除@XmlRootElement
注释,它们会在 POJO 映射打开时强制生成 XML。
Also have a look at my question regarding this: Java.util.Map to JSON Object with Jersey / JAXB / Hymanson
也看看我的问题:Java.util.Map to JSON Object with Jersey / JAXB / Hymanson
Reference: http://jersey.java.net/nonav/documentation/latest/json.html#d4e894
参考:http: //jersey.java.net/nonav/documentation/latest/json.html#d4e894
回答by StaxMan
You only need to use JAXB annotations if you also want to produce/consume data as XML.
如果您还想以 XML 形式生成/使用数据,则只需使用 JAXB 注释。
If you just care about JSON, do not use JAXB annotations; there is nothing they offer over and beyond Hymanson annotations. And in fact most of the time basic cases can be handled without any annotations by using Java Bean naming conventions.
如果只关心 JSON,请不要使用 JAXB 注释;除了Hyman逊注释之外,他们没有提供任何内容。事实上,大多数时候基本情况可以通过使用 Java Bean 命名约定在没有任何注释的情况下进行处理。