2011-02-17 58 views
2

我試圖用JSON使用RESTEasy對JAXB註釋類進行序列化。默認情況下,ResteasyJacksonProvider被配置爲僅使用JACKSON註釋。有沒有辦法配置ResteasyJacksonProvider使用JAXB註釋使用spring?有幾個編程方式,但寧願如果有一些彈簧配置。RESTEasy + Spring + Jackson + Jaxb

夫婦的方式,我爲ObjectMapper型思維

  1. 使用ContextResolver的返回ObjectMapper配置爲使用JaxbAnnotationIntrospector而不是JacksonAnnotationIntrospector。

  2. 擴展ResteasyJacksonProvider並在施工過程中傳遞JAXB註釋。

還有其他方法嗎?

回答

1

那麼使用ContextResolver的第一個選項的作品,但我仍然認爲應該有一個更簡單的方法來做到這一點只是通過一些配置。

0

你只能從配置中得到這個,不需要編程任何特殊的東西。 下面是如何: 首先設置你的配置吧,我用傑克遜+ JAXB,無論下ContentNegotiatingViewResolver豆設置:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 
     <property name="order" value="1"/> 
     <property name="mediaTypes"> 
      <map> 
       <entry key="xml" value="application/xml" /> 
       <entry key="json" value="application/json" /> 
      </map> 
     </property> 
     <property name="defaultViews"> 
      <list> 
       <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> 
        <property name="marshaller"> 
         <oxm:jaxb2-marshaller id="marshaller"> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.page.PageObject" /> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.tab.TabObject" /> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.section.SectionObject" /> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.element.nonembedded.ElementObject"/> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.element.embedded.EmbeddedElementObject"/> 
          <oxm:class-to-be-bound name="com.shay.dashboard.data.structure.chart.common.ChartManager"/> 
         </oxm:jaxb2-marshaller> 
        </property> 
       </bean> 
       <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/> 
      </list> 
     </property> 
    </bean> 

注意,編組下我設定的OXM:類待在一起 - 那些是JAXB綁定的類。

現在對於模塊,我使用了普通註釋包(javax.xml.bind.annotation),非編組特定。傑克遜Json和JAXB都知道如何閱讀它。

例如:

@XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name="page") public class PageObject implements ComponentTypeObject{ @XmlAttribute(name="name") private String name; @XmlAttribute(name="id",required=true) private String id;
@XmlElements({@XmlElement(name="tab", type=TabXmlAdapter.class)}) private List<TabXmlAdapter> tabRef;

最後,對於你的MVC控制器需要返回模型和視圖:

@RequestMapping(value="/get_page", method = RequestMethod.GET) 
public ModelAndView initPage() 
{ 
    ModelAndView mav = null; 
    try 
    { 
     PageObject myPage = (PageObject) Utilities.getUtilities().loadObjectFromFile(XmlComponentType.page); 
     mav = new ModelAndView("page","page",myPage); 
    } 
    catch (Exception e) 
    { 
     e.getMessage(); 
    } 
    return mav; 
} 

現在一邊撥打您的網址與上傳.json你會得到結束JSON表示,以及.xml和XML。如果在註釋模塊時給出了正確的映射,則兩者都由查看器翻譯。

+0

如果使用spring-web或spring-mvc進行調度,那麼您的解決方案可以工作。我正在使用RESTEasy。謝謝。 – Kamlesh 2011-03-10 19:56:11