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

如何为Java对象的OpenAPI @Schema注解设置对象类型示例?

解决对象类型属性OpenAPI示例格式问题

你遇到的问题核心在于@Schema的example属性是String类型,直接传入JSON字符串会被当作普通字符串解析,导致文档中显示带引号的字符串格式。以下是两种可行的解决方法:

方法一:在Person类上直接定义示例

在Person类本身添加@Schema注解并设置example,Employee中的person属性会自动继承该示例,生成的文档会以JSON对象格式展示:

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(example = "{\"age\": 30}")
public class Person {
    private Integer age;
    
    // getter、setter方法
}

public class Employee {
    @Schema
    private Person person;
    
    // 其他属性及方法
}

方法二:在Employee的person属性上使用@ExampleObject

如果不想修改Person类,可以在Employee的person属性上使用@Schema的examples属性,传入@ExampleObject对象,其value会被OpenAPI解析为JSON对象:

import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;

public class Employee {
    @Schema(examples = @ExampleObject(value = "{\"age\": 30}"))
    private Person person;
    
    // 其他属性及方法
}

这两种方法都能让生成的API文档中,person属性的示例以{"age": 30}的JSON对象格式展示,而非带引号的字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:32:33