@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,因此引发了以下错误:
位于0位置的意外字符(D)。设备标识符不能为空或空。
其中D在设备标识符中标记为红色,这意味着它不返回JSON作为响应。
发布于 2017-02-18 09:16:39
您的客户机希望获得JSON,但是您已经在响应实体中设置了一个普通字符串,并将application/json设置为内容类型。您需要返回一个有效的JSON。例如
return Response
.status(Response.Status.BAD_REQUEST)
.entity("{\"error\":\"Device cannot be null or empty.\"}")
.build();还可以使用首选映射程序构建json响应字符串(需要添加依赖项)。这是一个使用Jackson的例子。
使用API的Jackson
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("error", "Device cannot be null or empty.");
String json = mapper.writeValueAsString(objectNode);使用POJO的Jackson
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实现将它们转换为JSON (这意味着更改响应类型)。请参阅https://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
https://stackoverflow.com/questions/42295582
复制相似问题