Java 提供JSON/XML/etc响应的Web服务
当设计一个web服务,该服务应该返回相同数据的不同表示(如JSON、XML)时,您认为什么是最好的方法 要求将业务逻辑与写入实际XML/JSON响应的部分完全分离,具体取决于HTTP请求中接收到的“Accept”头 我认为这是许多web服务都存在的一个常见问题。Java 提供JSON/XML/etc响应的Web服务,java,xml,json,web-services,rest,Java,Xml,Json,Web Services,Rest,当设计一个web服务,该服务应该返回相同数据的不同表示(如JSON、XML)时,您认为什么是最好的方法 要求将业务逻辑与写入实际XML/JSON响应的部分完全分离,具体取决于HTTP请求中接收到的“Accept”头 我认为这是许多web服务都存在的一个常见问题。 有什么可以帮我的提示/设计模式/维基/项目吗?第一个问题是您想使用哪个HTTP协议:REST还是SOAP 使用REST时,我会创建一个服务,每个表示都有不同的使用者方法。 在这个REST服务背后,您可以让真正的服务和使用者方法调用完全相
有什么可以帮我的提示/设计模式/维基/项目吗?第一个问题是您想使用哪个HTTP协议:REST还是SOAP 使用REST时,我会创建一个服务,每个表示都有不同的使用者方法。 在这个REST服务背后,您可以让真正的服务和使用者方法调用完全相同的业务逻辑。 您可以根据要返回的表示形式修改路径 例如:
@GET
@Path("/json/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response readAsJson(@PathParam("id") String id) throws JAXBException {
final Object obj = dao.get(id);
if (obj == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(obj).build();
}
@GET
@Path("/xml/{id}")
@Produces(MediaType.APPLICATION_XML)
public Response readAsXml(@PathParam("id") String id) throws JAXBException {
final Object obj = dao.get(id);
if (obj == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(obj).build();
}
在应用程序中包括一个新的委托层,它将所有请求委托给服务层。 在ServiceDelegator类中,可以有多个方法(具有不同的返回类型),这些方法可以在内部调用服务的目标方法。 您的业务方法将存在于您的服务类中,其中ServiceDelegator类的多个方法将调用您服务的同一业务方法
@Path("/root")
public class ServiceDelegator{
@GET
@Path("/getDetailsAsXML")
@Produces(MediaType.APPLICATION_XML)
public Todo getDetailsAsXML() {
return new GetDetailsService().getDetails();
}
@GET
@Path("/getDetailAsJSON")
@Produces(MediaType.APPLICATION_JSON)
public Todo getDetailsAsJSON() {
return new GetDetailsService().getDetails();
}
}
public class GetDetailsService{ // your service class containing the business methods
public Todo getDetails() { // Todo is just a pojo return type which would finally be converted into either XML or JSON type based on the delegator method that invoked this service
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}
public class Todo {
private String summary;
private String description;
// Getters and Setters
}
另一种方法:
您可以使用多种返回类型(MediaType)声明服务方法,如下所述:
@Path("/root")
public class GetDetailsService{
@GET
@Path("/getDetails")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Todo getDetails() {
Todo todo = new Todo(); // Todo is just a pojo return type which would finally be converted into either XML or JSON type based on the "Accept" header of your HTTP request.
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}
public class Todo {
private String summary;
private String description;
// Getters and Setters
}
现在,将根据HTTP请求的“Accept”头返回JSON类型或XML类型。作为此答案的补充,soap始终序列化为XML。唯一的方法是手动将数据序列化为xml/json,作为soap:body(作为CDATA传递)的内容查看jax rs或restlet