Swagger API 使用 json 进行 json 验证

Swagger API consuming json with json validation

我正在使用 Swagger 生成 Restful API:

@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 对象之前,我如何验证传入的 json 字符串(针对 json 模式)?

因为您不想在您的方法和 Bean Validation is not an option for your validation, you could try a MessageBodyWriter<T> 中收到 JSON 字符串。

JAX-RS 使用 MessageBodyWriter<T>s to parse incoming requests. Since you want something very specific, consider writing your own MessageBodyWriter<T>

参见以下示例:

@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 注释使 class 在提供程序扫描阶段由 JAX-RS 运行时自动发现。

swagger-request-validator having several adapters for various frameworks, e.g.: Spring Web MVC

它能够验证针对 Swagger/OpenAPI 2 或 OpenAPI 3 方案的请求和/或响应。

请参阅此处: 以获得更详细的答案。