我使用Swagger来生成Restful:
@POST
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Create a task", notes = "", response = Tasks.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "created task", response = Tasks.class),
@io.swagger.annotations.ApiResponse(code = 404, message = "task not found", response = Tasks.class),
@io.swagger.annotations.ApiResponse(code = 200, message = "unexpected error", response = Tasks.class) })
public Response createTask(@ApiParam(value = "The task to create" ,required=true ) NewTask newTask)
throws NotFoundException {
return delegate.createTask(newTask);
}这个API接受json字符串并从它生成java对象。这是很好的工作,只有一个例外: API接受任何正确的格式的json字符串,但忽略json的内容,这意味着我创建了一个带有默认值的对象。
因此,我的问题是:在生成实际的java对象之前,如何验证传入的jsonstring (针对json模式)?
发布于 2015-12-01 14:39:33
由于不希望在方法中接收JSON字符串,而且Bean验证不是验证的选项,所以可以尝试使用MessageBodyWriter。
JAX使用S来解析传入的请求。既然您想要一些非常具体的内容,请考虑MessageBodyWriter。
请参见以下示例:
@Provider
@Produces("application/json")
public class CustomMessageBodyWriter implements MessageBodyWriter<Object> {
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public long getSize(MyBean myBean, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
// Deprecated by JAX-RS 2.0
return 0;
}
@Override
public void writeTo(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException {
// Read the entityStream
// Perform the validation against your schema
// Write to the object
}
}@Provider注释使JAX运行时在提供者扫描阶段自动发现该类。
发布于 2019-10-03 09:39:40
斯威格-请求-验证器有几个用于不同框架的适配器,例如:Spring Web MVC
它能够根据Swagger / OpenAPI 2或OpenAPI 3方案验证请求和/或响应。
更详细的答案见这里:根据Java中Swagger定义验证JSON消息。
https://stackoverflow.com/questions/34019825
复制相似问题