rest。 新泽西州。 如何以编程方式选择要返回的类型:JSON还是XML?
我有两个问题:
1.我可以创建一个类,使用JAXB注释(对于XML支持)进行注释,并在web.xml
声明
com.sun.jersey.api.json.POJOMappingFeature true
对于JSON(jackson图书馆)的支持? 或者我需要为JSON和XML单独创建两个类?
或者可能存在一些更优雅的方式来使REST服务返回JSON和XML?
2.我如何以编程方式选择要返回的类型(JSON或XML)?
谢谢。
如果您的客户端想要使用URL的一部分来配置响应类型,则可以使用Servletfilter。
实现覆盖表示(媒体类型)的简单方法可以使用URL查询参数:
/资源/待办事项?格式= JSON
Servletfilter解析URL查询参数,如果存在format = json,则替换或添加accept标头“application / json”。
注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员。
我可以创建一个类,使用JAXB注释(对于XML支持)进行注释,并在web.xml中声明JSON(jackson库)支持吗?
您始终可以使用Application
类为JSON绑定指定MessageBodyReader
/ MessageBodyWriter
。 我相信jackson在其jar中提供了一个实现。 下面是一个Application
类的示例,它将MOXy指定为JSON提供者:
package org.example; import java.util.*; import javax.ws.rs.core.Application; import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider; public class CustomerApplication extends Application { @Override public Set> getClasses() { HashSet> set = new HashSet>(2); set.add(MOXyJsonProvider.class); set.add(CustomerService.class); return set; } }
或者我需要为JSON和XML单独创建两个类?
EclipseLink JAXB(MOXy)提供本机XML绑定,旨在使您能够为JSON和XML使用相同的对象模型 。 您可以使用MOXyJsonProvider
类将其集成到JAX-RS应用程序中:
我如何以编程方式选择要返回的类型(JSON或XML)?
服务器端
您可以使用@Produces
批注指定您的服务同时提供XML和JSON消息。
@GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("{id}") public Customer read(@PathParam("id") long id) { return entityManager.find(Customer.class, id); }
欲获得更多信息
客户端
您可以使用MediaType指示消息的类型。 以下是使用Jersey客户端API的示例。 请注意URL是如何相同的,只是请求的媒体类型不同。
Client client = Client.create(); WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers"); // Get XML response as a Customer Customer customer = resource.path("1") .accept(MediaType.APPLICATION_XML) .get(Customer.class); System.out.println(customer.getLastName() + ", "+ customer.getFirstName()); // Get JSON response as a Customer Customer customer = resource.path("1") .accept(MediaType.APPLICATION_JSON) .get(Customer.class); System.out.println(customer.getLastName() + ", "+ customer.getFirstName());
欲获得更多信息
不需要单独的课程,你需要的是单独的方法:
@GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Todo getXML() { Todo todo = new Todo(); todo.setSummary("This is my first todo"); todo.setDescription("This is my first todo"); return todo; }
然后在客户端,当您请求服务时,您指明您想要的格式:
// Get XML System.out.println(service.path("rest").path("todo").accept(MediaType.TEXT_XML).get(String.class)); // Get XML for application System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_XML).get(String.class)); // Get JSON for application System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_JSON).get(String.class));