Reputation: 3577
I need to define a map. But I also want to limit the possible keys.
Here is what I tried to do.
type: object
description: Key Value Map with user data. Possible values for the keys ("KEY_1", "KEY_2", "KEY_3")
additionalProperties:
type: object
Is it possible to use an enumeration to define the keys ? (the map returns int String, Object. But this is not part of the problem)
Thank you for your help.
Upvotes: 14
Views: 12547
Reputation: 5271
When you use additionalProperties
you cannot define the set of accepted keys. But if my understanding is correct, two example of this hashmap as JSON could be:
JSON example 1:
{
"KEY_1": { ... },
"KEY_2": { ... },
"KEY_3": { ... }
}
JSON example 2:
{
"KEY_1": { ... },
"KEY_3": { ... }
}
This hashmap with a defined set of key is basically an object which contains optional (i.e. non required) properties of type object and therefore could be defined just like any other object:
type: object
properties:
KEY_1:
type: object
KEY_2:
type: object
KEY_3:
type: object
nb: it would be a good idea to use a $ref to avoid having to define the object for each KEY property:
type: object
properties:
KEY_1:
$ref: '#/definitions/TheObjectDefinition'
KEY_2:
$ref: '#/definitions/TheObjectDefinition'
KEY_3:
$ref: '#/definitions/TheObjectDefinition'
Upvotes: 7
Reputation: 644
You can simulate a dictionary/map using a list.
First you define an entry object, where you can restrict types.
Then you define a map as an array of entries.
Entry:
type: object
properties:
key:
$ref: '#/components/schemas/SomeEnum'
value:
type: string
SimulatedMap:
type: object
properties:
entries:
type: array
items:
$ref: '#/components/schemas/Entry'
Upvotes: -1