Alo*_*ras 3 java json return response jax-rs
我有一个使用jax-rs的Web服务,我的服务返回一个对象列表,但是您不知道如何添加自定义状态值来响应,例如,我要构建的结果如下:
如果可以:
{
"status": "success",
"message": "list ok!!",
"clients": [{
"name": "john",
"age": 23
},
{
"name": "john",
"age": 23
}]
}
Run Code Online (Sandbox Code Playgroud)
如果是错误:
{
"status": "error",
"message": "not found records",
"clients": []
}
Run Code Online (Sandbox Code Playgroud)
我的休息服务:
@POST
@Path("/getById")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<Client> getById(Client id) {
try {
return Response.Ok(new ClientLogic().getById(id)).build();
//how to add status = success, and message = list! ?
} catch (Exception ex) {
return ??
// ex.getMessage() = "not found records"
//i want return json with satus = error and message from exception
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想在输出JSON结构的完全控制,使用JsonObjectBuilder(如解释在这里,那么你最终的JSON转换为字符串,并写入(例如,对于成功的JSON):
return Response.Ok(jsonString,MediaType.APPLICATION_JSON).build();
Run Code Online (Sandbox Code Playgroud)
并将您的返回值更改为Response对象。
但是请注意,您正在尝试发送冗余(而非标准)信息,该信息已被编码为HTTP错误代码。当您使用Response.Ok时,响应将具有代码“ 200 OK”,并且您可以研究Response类的方法以返回所需的任何HTTP代码。您的情况是:
return Response.status(Response.Status.NOT_FOUND).entity(ex.getMessage()).build();
Run Code Online (Sandbox Code Playgroud)
返回404 HTTP代码(请查看Response.Status代码列表)。
我遇到了同样的问题,这是我解决它的方法。如果您的服务方法成功,则返回 Response 状态为 200 和您想要的实体。如果您的服务方法抛出异常,则返回具有不同状态的响应,并将异常消息绑定到您的 RestError 类。
@POST
@Path("/getById")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getById(Client id) {
try {
return Response.Ok(new ClientLogic().getById(id)).build();
} catch (Exception ex) {
return Response.status(201) // 200 means OK, I want something different
.entity(new RestError(status, msg))
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我使用这些实用程序方法从响应中读取实体。如果有错误,我会抛出一个异常,其中包含该错误的状态和 msg。
public class ResponseUtils {
public static <T> T convertToEntity(Response response,
Class<T> target)
throws RestResponseException {
if (response.getStatus() == 200) {
return response.readEntity(target);
} else {
RestError err = response.readEntity(RestError.class);
// my exception class
throw new RestResponseException(err);
}
}
// this method is for reading Set<> and List<> from Response
public static <T> T convertToGenericType(Response response,
GenericType<T> target)
throws RestResponseException {
if (response.getStatus() == 200) {
return response.readEntity(target);
} else {
RestDTOError err = response.readEntity(RestError.class);
// my exception class
throw new RestResponseException(err);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的客户端方法将调用(通过代理对象)服务方法
public List<Client> getById(Client id)
throws RestResponseException {
return ResponseUtils.convertToGenericType(getProxy().getById(id),
new GenericType<List<Client>>() {});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7448 次 |
| 最近记录: |