简体   繁体   English

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

[英]Return JSON data type/view from Spring controller

How do I convert an existing XML-based web service to JSON-type web service? 如何将现有的基于XML的Web服务转换为JSON类型的Web服务?

I have this sample resource: 我有以下示例资源:

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

So far, I am not experiencing any error with regards to accessing it, I just want to change the data that this service return to the client from XML to JSON. 到目前为止,关于访问它,我还没有遇到任何错误,我只想将此服务返回给客户端的数据从XML更改为JSON。

With this entity: 使用此实体:

@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: 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>

How can I change the output of the service to JSON? 如何将服务的输出更改为JSON? Do I need to put JSON-type annotations in the entity/model? 我是否需要在实体/模型中放入JSON类型的注释?

Using Jackson JSON processor , your code would remarkably similar. 使用Jackson JSON处理器 ,您的代码将非常相似。 The model will be in simple POJO format. 该模型将采用简单的POJO格式。 Use @ResponseBody for your response again and Jackson will take care of the JSON conversion. 再次使用@ResponseBody进行响应,Jackson将负责JSON转换。

See this Spring 3 MVC and JSON example . 请参阅此Spring 3 MVC和JSON示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM