2011-01-19 113 views
3

我想在我的基於RESTEasy的web應用程序中啓用JAXB註釋支持,並向我提供了這篇文章(http://wiki.fasterxml.com/JacksonJAXBAnnotations)。我能夠得到jackson-xc.jar,但我看不到如何註冊annotation introspector。目前,RESTEasy會自動序列化我的JSON響應,下面哪裏適合?目前,RESTeasy會自動序列化JSON對象。使用Jackson JSON庫和JAXB註釋

包括傑克遜-XC罐子,其中包含org.codehaus.jackson.xc.JaxbAnnotationIntrospector 註冊此註釋內省

ObjectMapper mapper = new ObjectMapper(); 
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); 
    // make deserializer use JAXB annotations (only) 
    mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); 
    // make serializer use JAXB annotations (only) 
    mapper.getSerializationConfig().setAnnotationIntrospector(introspector); 

回答

2

你需要弄清楚的是如何使RestEasy的使用ObjectMapper你已經配置。 JAX-RS提供了通過提供程序完成此操作的通用方式,但使用RESTeasy可能會有更簡單的方法。某些JAX-RS實現默認情況下也會註冊JAXB註釋introspector。

最後一件事:你確定你需要使用JAXB註釋嗎?雖然傑克遜可以使用它們,但最好的方法是在發現和傑克遜自己的註釋中使用基本的命名約定,以便在需要覆蓋的情況下使用。 JAXB的問題在於它是特定於xml的,因此與JSON一起使用時阻抗很小。

1

感謝您的答覆,我就看看你的建議...

我們之所以要堅持與JAXB註釋是,@XmlRootElement(name =「userResponse」)註釋允許一個額外的包裝元素,我們需要在我們的JSON響應。請參閱下面的示例:

我們希望{「response」:{「userResponse」:[{「user」:{「businessRegion」:「US」,「firstName」:「joe」,「language」 :「en」,「lastName」:「smith」}}}]}而不是Jackson目前的輸出結果,{「response」:[「user」:{「businessRegion」:「US」,「firstName」:「joe 」, 「語言」: 「恩」, 「姓氏」: 「史密斯」}}]}。無論如何,無需添加額外的包裝類,就可以在Jackson中模仿@XmlRootElement?

用戶類: @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(名稱= 「userResponse」) 公共類UserResponse延伸AbstractResponse { 私人用戶的用戶;

+0

好的。這樣的包裝是由RESTeasy完成的,因爲即使使用JAXB註釋,傑克遜也不這樣做;但是一些框架可以幫助確定在根級別綁定哪種類型。對於它的價值,這樣的包裝很容易處理簡單的包裝類,或使用java.lang.Map;所以這可能不需要使用@XmlRootElement。但可能有其他原因使用它。 – StaxMan 2011-01-21 04:56:57