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

如何用NelmioApiDocBundle和Swagger描述含嵌套对象的API响应

完善Swagger注解描述嵌套对象响应

别担心,我这就帮你把Swagger注解补全,完美描述包含嵌套Car对象的Person响应结构。核心思路是先给嵌套的子对象单独定义Swagger实体,然后在父对象里引用它,这样结构清晰还能复用。

第一步:定义嵌套的Car类注解

先给Car类加上完整的Swagger定义,让Swagger能识别这个嵌套对象的结构:

use Swagger\Annotations as SWG;

/**
 * @SWG\Definition(
 *     definition="Car",
 *     title="Car",
 *     description="用户拥有的车辆信息"
 * )
 */
class Car
{
    /**
     * @SWG\Property(
     *     title="brand",
     *     type="string",
     *     description="汽车品牌"
     * )
     */
    protected $brand;

    /**
     * @SWG\Property(
     *     title="price",
     *     type="string",
     *     description="汽车价格"
     * )
     */
    protected $price;

    // 按需添加getter/setter方法
}

第二步:完善Person类的注解

接下来修正你原来Person类里的小问题(比如required={"true"}的写法错误,还有description和字段不匹配的问题),并引用上面定义的Car对象:

use Swagger\Annotations as SWG;

/**
 * @SWG\Definition(
 *     definition="Person",
 *     title="Person",
 *     description="用户个人信息"
 * )
 */
class Person
{
    /**
     * @SWG\Property(
     *     title="firstName",
     *     type="string",
     *     required=true, // 注意这里是布尔值,不是字符串数组
     *     description="用户的名字"
     * )
     */
    protected $firstName;

    /**
     * @SWG\Property(
     *     title="lastName",
     *     type="string",
     *     required=true,
     *     description="用户的姓氏"
     * )
     */
    protected $lastName;

    /**
     * @SWG\Property(
     *     title="car",
     *     ref="#/definitions/Car", // 引用之前定义的Car实体
     *     description="用户拥有的车辆"
     * )
     */
    protected $car;

    // 按需添加getter/setter方法
}

第三步:在控制器里定义API响应

最后在你的API控制器方法里,用Swagger注解指定响应结构,这样就能在文档里看到完整的嵌套JSON示例了:

use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Response;

/**
 * @SWG\Get(
 *     path="/api/person/{id}",
 *     summary="获取单个用户信息",
 *     @SWG\Response(
 *         response=Response::HTTP_OK,
 *         description="成功获取用户信息",
 *         @SWG\Schema(ref="#/definitions/Person")
 *     )
 * )
 */
public function getPerson(int $id): Response
{
    // 你的业务逻辑,返回Person对象
}

这样配置后,Swagger文档里就会生成和你给出的示例完全一致的JSON结构:

{
  "firstName": "John",
  "lastName": "Smith",
  "car": {
    "brand": "Tesla",
    "price": "1000"
  }
}

另外提两个小细节:

  • 你原来的代码里required={"true"}是错误的写法,Swagger的required参数接受布尔值或者字段名数组(比如required={"firstName", "lastName"}),单个字段直接写required=true就可以。
  • 原来的firstName字段的description写的是"Last Name",我已经帮你修正成匹配的描述了,记得保持字段和描述对应哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:21:40