Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to describe datatypes.JSON datatype for go in openAPI Spec?

I have a golang-gin project. where there is a structure like this:

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

The QuesAns field should have the JSON of any of these three types.

"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" 
     ] 
 }

How do you describe this for integrating open API Spec?

I have tried with several types but cannot sync all of them, as the JSON can be of different types, and only these three types will be valid.

like image 948
mimi0007 Avatar asked Dec 22 '25 06:12

mimi0007


1 Answers

Ok! I solved it in this way:

components:
  schemas:
    Value:
      type: object
      properties:
        ques_ans:
          oneOf:
            - $ref: '#/components/schemas/Type1'
            - $ref: '#/components/schemas/Type2'
            - $ref: '#/components/schemas/Type3'
    Type1:
      type: object
      properties:
        receiver.ques:
          type: array
          items:
            type: string
        receiver.ans:
          type: array
          items:
            type: string
    Type2:
      type: object
      properties:
        id:
          type: string
        receiver.sid:
           type: string
        receiver.ques:
          type: array
          items:
            type: string
    Type3:
      type: object
      properties:
        receiver.ques_key:
          type: array
          items:
            type: string
        receiver.ans_key:
          type: array
          items:
            type: string
    
like image 178
mimi0007 Avatar answered Dec 23 '25 23:12

mimi0007