2012-08-01 51 views
0

如何將現有的基於XML的Web服務轉換爲JSON類型的Web服務?從Spring控制器返回JSON數據類型/視圖

我有這樣的樣本資源:

@Controller 
public class CustomerController { 
    @RequestMapping(value="customers", method=RequestMethod.GET) 
    public @ResponseBody CustomerList customers(Model model) { 
     CustomerList list = new CustomerList(); 
     list.getCustomer().add(new Customer("1", "John Doe")); 
     list.getCustomer().add(new Customer("2", "Jane Doe")); 
     return list; 
    } 
} 

到目前爲止,我沒有遇到任何錯誤至於訪問它,我只是想改變數據,該服務返回給客戶端從XML到JSON 。

有了這個實體:

@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "", propOrder = { 
    "customer" 
}) 
@XmlRootElement(name = "CustomerList") 
public class CustomerList { 

    @XmlElement(name = "Customer", required = true) 
    protected List<Customer> customer; 

    public List<Customer> getCustomer() { 
     if (customer == null) { 
      customer = new ArrayList<Customer>(); 
     } 
     return this.customer; 
    } 

} 

的servlet-context.xml中:

<oxm:jaxb2-marshaller id="marshaller" contextPath="com.mycompany.api.model"/> 
<beans:bean id="customerList" class="org.springframework.web.servlet.view.xml.MarshallingView"> 
     <beans:constructor-arg ref="marshaller"/> 
</beans:bean> 

我怎樣才能改變服務JSON的輸出?我是否需要將JSON類型的註釋放入實體/模型中?

回答

0

使用Jackson JSON processor,您的代碼將非常相似。該模型將採用簡單的POJO格式。再次使用@ResponseBody作爲您的迴應,Jackson將負責JSON轉換。

看到這個Spring 3 MVC and JSON example

+0

根據我所看到的,我從您提供的鏈接中的示例代碼中提供的代碼的唯一區別在於我使用了XML編組視圖。刪除該標籤我得到這個錯誤:警告:/ customers java.security.AccessControlException:access denied(「javax.xml.bind.JAXBPermission」「setDatatypeConverter」) – xybrek 2012-08-01 11:34:04

+0

如果您有雙重響應類型,那麼您可以使用ContentNegotiatingViewResolver http://stackoverflow.com/questions/6467119/spring-mvc-rest-response-json-and-xml – Reimeus 2012-08-01 11:51:28

+0

對,我通過刪除實體/模型中的Jaxb註釋來解決了這個問題。雙重響應也可能是一個不錯的選擇。 – xybrek 2012-08-01 15:59:01

相關問題