Din*_*uka 2 java rest google-app-engine jax-rs restful-architecture
我试图在Eclipse中使用JAX-RS从Java REST API方法返回多个对象(如String,Boolean,MyOwnClass等).
这就是我现在所拥有的:
我的API方法
@Path("/")
public class myAPI {
@GET
@Produces({ "application/xml", "application/json" })
@Path("/getusers")
public Response GetAllUsers() {
//Data Type #1 I need to send back to the clients
RestBean result = GetAllUsers();
//Data Type #2 I need to send with in the response
Boolean isRegistered = true;
//The following code line doesn't work. Probably wrong way of doing it
return Response.ok().entity(result, isRegistered).build();
}
}
Run Code Online (Sandbox Code Playgroud)
RestBean类:
public class RestBean {
String status = "";
String description = "";
User user = new User();
//Get Set Methods
}
Run Code Online (Sandbox Code Playgroud)
所以我基本上发送两种数据类型:RestBean和Boolean.
使用多个数据对象发回JSON响应的正确方法是什么?
首先,Java约定是类名以大写字母开头,方法名称以小写字母开头.遵循它们通常是个好主意.
正如@Tibrogargan建议的那样,您需要将响应包装在单个类中.
public class ComplexResult {
RestBean bean;
Boolean isRegistered;
public ComplexResult(RestBean bean, Boolean isRegistered) {
this.bean = bean;
this.isRegistered = isRegistered;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的资源看起来像......
public Response getAllUsers() {
RestBean restBean = GetAllUsers();
Boolean isRegistered = true;
final ComplexResult result = new ComplexResult(bean, isRegistered);
return Response.ok().entity(Entity.json(result)).build();
}
Run Code Online (Sandbox Code Playgroud)
但是,您真正需要知道的是您的响应文档应该是什么样子.您只能拥有一个响应文档 - 这是包装器的用途 - 并且您的包装器的序列化方式会影响文档各部分的访问方式.
注意 - 您已将资源列为能够生成XML和JSON,并且我所做的只适用于json.您可以让框架为您完成所有内容协商繁重的工作,这可能是一个好主意,只需从方法中返回文档类型而不是Response...
public ComplexResponse getAllUsers() {
...
return new ComplexResult(bean, isRegistered);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4786 次 |
| 最近记录: |