@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("/data/services")
public Response DiscoverDevice(BlockDevsPost blockdevice) {
for (DeviceIdentifier device : blockdevice.getDevice()) {
String dev = device.Device();
System.out.println("DEVICE "+ dev);
if (dev == null || dev.equals("")){
return Response.status(Response.Status.BAD_REQUEST).entity("Device cannot be null or empty.").build();
}
}
}
当 dev
为 null 时从 REST 客户端触发 POST 时出现此错误。我无法获取 JSON 并且抛出此错误:
Unexpected character (D) at position 0. Device Identifier cannot be null or empty.
设备标识符中的 D 标记为红色,这意味着它不会返回 JSON 作为响应。
最佳答案
您的客户端期望获取 JSON,但您已在响应实体中设置了一个纯字符串,并将 application/json
设置为内容类型。您需要返回一个有效的 JSON。例如
return Response
.status(Response.Status.BAD_REQUEST)
.entity("{\"error\":\"Device cannot be null or empty.\"}")
.build();
您还可以使用您首选的映射器构建 json 响应字符串(您将需要添加依赖项)。这是使用 Jackson 的示例
jackson 使用 API
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("error", "Device cannot be null or empty.");
String json = mapper.writeValueAsString(objectNode);
jackson 使用 POJO
class ErrorBean{
private String error;
//getters and setters
}
ObjectMapper mapper = new ObjectMapper();
ErrorBeanerrorBean = new ErrorBean();
errorBean.setError ("Device cannot be null or empty.");
String json = mapper.writeValueAsString(errorBean);
您还可以从服务方法返回 POJO,并让 JAX-RS 实现将它们转换为 JSON(这意味着更改响应类型)。请参阅https://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
关于java - 错误 - 返回 JSON 以及 HTTP 状态代码错误 JAX-RS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295582/