Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

dictionary - Swagger HashMap property type

Is there any way to define a HashMap or Generic Object type in the models section? I have a REST service that returns products and those products can have different options. The options property are basically a HashMap, where the id is the option name and its value is the option value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it's possible.

In OpenAPI (fka. Swagger) 2.0 and 3.0, a hashmap is always a <string, something> map:

  • The key is always a string and do not need to be defined.
  • The value type is what you want and is defined with additionalProperties.

Let's say you want to describe a <string, string> hashmap like this one:

{
  "key1": "value1",
  "key2": "value2"
}

The corresponding OpenAPI 2.0 definition will be:

definitions:
  StringStringMap:
    type: object
    additionalProperties:
      type: string

In OpenAPI 3.0 the definition will be:

components:
  schemas:
    StringStringMap:
      type: object
      additionalProperties:
        type: string


A <string, object> hashmap like this

{
  "key1": {"someData": "data", "someOtherData": true},
  "key2": {"someData": "data2", "someOtherData": false}
}

will be defined this way in OpenAPI 2.0:

definitions:
  ComplexObject:
    type: object
    properties:
      someData:
        type: string
      someOtherData:
        type: boolean

  StringObjectMap:
    type: object
    additionalProperties:
      $ref: "#/definitions/ComplexObject"

and in OpenAPI 3.0:

components:
  schemas:
    ComplexObject:
      type: object
      properties:
        someData:
          type: string
        someOtherData:
          type: boolean

    StringObjectMap:
      type: object
      additionalProperties:
        $ref: "#/definitions/ComplexObject"

I've just covered this in depth in part 4 of my OpenAPI (fka Swagger tutorial).

The OpenAPI (fka. Swagger) specification explains briefly this too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...