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

如何在OpenAPI规范中描述Golang Gin项目的datatypes.JSON字段?

在OpenAPI中描述多格式的JSON字段(Golang-Gin场景)

我有一个Golang-Gin项目,其中包含如下结构体:

type Value struct { 
    gorm.Model 
    QuesAns       datatypes.JSON `json:"ques_ans"` 
}

QuesAns字段的JSON值仅允许为以下三种合法格式之一:

格式一:

"ques_ans": {
    "receiver.ques": [
         "Q1",
         "Q2"
     ], 
    "receiver.ans": [
         "Ans1",
         "Ans2",
         "Ans3" 
     ]
 }

格式二:

"ques_ans": {
     "id": "1",
     "receiver.sid": "2743dfjfh87",
     "receiver.ques": [
         "Q1",
         "Q2",
         "Q3" 
     ] 
 }

格式三:

"ques_ans": {
     "receiver.ques_key": [
         "1",
         "2" 
     ],
     "receiver.ans_key": [
         "13",
         "20" 
     ] 
 }

尝试多种类型定义后无法同时适配这三种格式,请问如何在OpenAPI规范中对此字段进行描述?


解决方案

你可以利用OpenAPI规范中的oneOf关键字来定义这个支持多格式的字段,oneOf用于表示字段值必须匹配其中一个指定的Schema。以下是具体的OpenAPI描述示例:

components:
  schemas:
    Value:
      type: object
      properties:
        # 可补充gorm.Model对应的字段(如id、created_at等),根据实际业务调整
        ques_ans:
          oneOf:
            - $ref: '#/components/schemas/QuesAnsFormat1'
            - $ref: '#/components/schemas/QuesAnsFormat2'
            - $ref: '#/components/schemas/QuesAnsFormat3'
          description: 支持三种合法格式的问答数据

    QuesAnsFormat1:
      type: object
      required:
        - receiver.ques
        - receiver.ans
      properties:
        receiver.ques:
          type: array
          items:
            type: string
        receiver.ans:
          type: array
          items:
            type: string
      additionalProperties: false # 如需禁止额外字段可添加,允许则删除该行

    QuesAnsFormat2:
      type: object
      required:
        - id
        - receiver.sid
        - receiver.ques
      properties:
        id:
          type: string
        receiver.sid:
          type: string
        receiver.ques:
          type: array
          items:
            type: string
      additionalProperties: false

    QuesAnsFormat3:
      type: object
      required:
        - receiver.ques_key
        - receiver.ans_key
      properties:
        receiver.ques_key:
          type: array
          items:
            type: string
        receiver.ans_key:
          type: array
          items:
            type: string
      additionalProperties: false

关键说明

  • oneOf确保ques_ans字段值严格匹配三个Schema中的某一个,三种格式结构差异明显,无需使用允许部分重叠匹配的anyOf。
  • 每个子Schema通过required指定该格式下必须存在的字段,保证格式合法性。
  • 若使用swaggo等工具自动生成OpenAPI文档,可在Go结构体注释中通过// swagger:model和对应注解映射上述定义,具体参考工具官方文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:45:15