【问题标题】:Return JSON data type/view from Spring controller从 Spring 控制器返回 JSON 数据类型/视图
【发布时间】:2012-08-01 10:44:12
【问题描述】:

如何将现有的基于 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;
    }

}

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 类型的注释吗?

【问题讨论】:

    标签: java json web-services spring


    【解决方案1】:

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

    看到这个Spring 3 MVC and JSON example

    【讨论】:

    • 据我所知,我提供的代码与您提供的链接中的示例代码的唯一区别是我使用了 XML Marshalling 视图。删除该标签我收到此错误:警告:/customers java.security.AccessControlException:访问被拒绝(“javax.xml.bind.JAXBPermission”“setDatatypeConverter”)
    • 如果您有双重响应类型,那么您可以使用 ContentNegotiatingViewResolver 例如stackoverflow.com/questions/6467119/…
    • 对,我通过删除实体/模型中的 Jaxb 注释解决了这个问题。双重响应也可能是一个不错的选择。
    猜你喜欢
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多