Java 从Spring控制器返回JSON数据类型/视图

Java 从Spring控制器返回JSON数据类型/视图,java,json,web-services,spring,Java,Json,Web Services,Spring,如何将现有的基于XML的web服务转换为JSON类型的web服务 我有以下示例资源: @Controller public class CustomerController { @RequestMapping(value="customers", method=RequestMethod.GET) public @ResponseBody CustomerList customers(Model model) { CustomerList list = new C

如何将现有的基于XML的web服务转换为JSON类型的web服务

我有以下示例资源:

@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;
    }

}
@xmlacessortype(xmlacesstype.FIELD)
@XmlType(name=),比例={
“客户”
})
@XmlRootElement(name=“CustomerList”)
公共类客户列表{
@xmlement(name=“Customer”,required=true)
受保护名单客户;
公共列表getCustomer(){
如果(客户==null){
客户=新的ArrayList();
}
将此文件退回给客户;
}
}
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类型的注释

使用,您的代码将非常相似。模型将采用简单的POJO格式。再次使用@ResponseBody进行响应,Jackson将负责JSON转换


看看这个。

从我所看到的,我提供的代码与您提供的链接中的示例代码的唯一区别是我使用了XML编组视图。删除该标记会出现以下错误:警告:/customers java.security.AccessControlException:access denied(“javax.xml.bind.jaxpermission”“setDatatypeConverter”)如果您具有双重响应类型,则可以使用ContentNegotingViewResolver。例如,对,我通过删除实体/模型中的Jaxb注释修复了该问题。双重反应可能也是一个不错的选择。