你只能從配置中得到這個,不需要編程任何特殊的東西。 下面是如何: 首先設置你的配置吧,我用傑克遜+ 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。如果在註釋模塊時給出了正確的映射,則兩者都由查看器翻譯。
如果使用spring-web或spring-mvc進行調度,那麼您的解決方案可以工作。我正在使用RESTEasy。謝謝。 – Kamlesh 2011-03-10 19:56:11