You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swagger中为byte[]类型@ArraySchema指定@ExampleObject示例

报错根因

你的Schema定义和示例值类型不匹配:
OpenAPI 规范里 type = "string", format = "byte" 本身指代的是Base64编码后的二进制字符串,类型为字符串,不是单个字节对应的数值。你配置的示例是数字构成的数组[104, 111, 108, 97],数组元素是数字类型,和Schema要求的字符串类型冲突,自然会报"property type must be string"的校验错误。

正确配置方法

根据接口实际的响应格式二选一即可:

场景1:接口返回二进制流(文件下载场景,是byte[]最常用的场景)

如果接口是直接返回文件、二进制内容,不返回JSON结构,不需要配置ArraySchema,直接指定schema为string/byte类型即可,示例值填对应字节序列的Base64编码结果,同时显式声明响应媒体类型为二进制流,避免Swagger按JSON格式校验:

@Operation(summary = "获取文档",
    responses = {
        @ApiResponse(responseCode = "200",
            content = @Content(
                mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE,
                schema = @Schema(type = "string", format = "byte"),
                examples = @ExampleObject(value = "aG9sYQ==") // 是字节[104,111,108,97]的Base64编码结果,解码后为字符串"hola"
            )
        )
    }
)

场景2:接口返回JSON格式的字节数字数组

如果接口响应本身就是JSON结构,内容是0-255区间数字组成的数组(即[104, 111, 108, 97]这种格式),就不要用string/byte的Schema定义,直接声明数组元素为整数类型即可:

@Operation(summary = "获取文档字节数组",
    responses = {
        @ApiResponse(responseCode = "200",
            content = @Content(
                mediaType = MediaType.APPLICATION_JSON_VALUE,
                array = @ArraySchema(schema = @Schema(type = "integer", format = "int32", minimum = "0", maximum = "255")),
                examples = @ExampleObject(value = "[104, 111, 108, 97]")
            )
        )
    }
)

这种配置下Schema和示例值类型完全匹配,不会触发校验报错。

内容的提问来源于stack exchange,提问作者user3083022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 11:36:21