2012-08-01 53 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

相关问题