首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用json验证的Swagger消费json

使用json验证的Swagger消费json
EN

Stack Overflow用户
提问于 2015-12-01 11:53:57
回答 2查看 2.4K关注 0票数 1

我使用Swagger来生成Restful:

代码语言:javascript
复制
@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模式)?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-01 14:39:33

由于不希望在方法中接收JSON字符串,而且Bean验证不是验证的选项,所以可以尝试使用MessageBodyWriter

JAX使用S来解析传入的请求。既然您想要一些非常具体的内容,请考虑MessageBodyWriter

请参见以下示例:

代码语言:javascript
复制
@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运行时在提供者扫描阶段自动发现该类。

票数 1
EN

Stack Overflow用户

发布于 2019-10-03 09:39:40

斯威格-请求-验证器有几个用于不同框架的适配器,例如:Spring Web MVC

它能够根据Swagger / OpenAPI 2或OpenAPI 3方案验证请求和/或响应。

更详细的答案见这里:根据Java中Swagger定义验证JSON消息

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34019825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档