Newbie
Newbie

Reputation: 741

How to define JSON Schema for Map<String, Integer>?

I have a json :

{
    "itemTypes": {
        "food": 22,
        "electrical": 2
    },
    "itemCounts": {
        "NA": 211
    }
}

Here the itemTypes and itemCounts will be common but not the values inside them (food, NA, electrical) which will be keep changing but the will be in the format : Map<String, Integer>

How do I define Json Schema for such generic structure ?

I tried :

"itemCounts": {
    "type": "object""additionalProperties": {
        "string",
        "integer"
    }
}

Upvotes: 26

Views: 60211

Answers (4)

Jay99
Jay99

Reputation: 111

using "additionalProperties" has 2 problems

  1. It creates additional class that represents Object or Int Map which internally has additionalProperty as member to be used as Map
  2. because its additionalProperties, it always has @JsonIgnore so it wont appear while serialization.

so In my opinion, The right approach would be to use direct Java Type.

"properties": {
  "myFieldName": {
    "existingJavaType" : "java.util.Map<String,String>",
    "type" : "object"
  }
}

ref: https://www.jsonschema2pojo.org/

Upvotes: 2

franleplant
franleplant

Reputation: 639

The question is kind of badly described, let me see if I can rephrase it and also answer it.

Question: How to Represent a map in json schema like so Map<String, Something>

Answer:

It looks like you can use Additional Properties to express it https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

{
  "type": "object",
  "additionalProperties": { "type": "something" }
}

For example let's say you want a Map<string, string>

{
  "type": "object",
  "additionalProperties": { "type": "string" }
}

Or something more complex like a Map<string, SomeStruct>

{
  "type": "object",
  "additionalProperties": { 
    "type": "object",
    "properties": {
      "name": "stack overflow"
    }
  }
}

Upvotes: 6

swarnim gupta
swarnim gupta

Reputation: 231

{
    "type": "array",
    "maxItems": 125,
    "items": {
        "type": "array",
        "items": [
            { // key schema goes here },
            { // value schema goes here }
        ],
        "additionalItems": false
    }
}

Upvotes: -4

esp
esp

Reputation: 7717

You can:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}

Upvotes: 39

Related Questions