Search code examples
jsonjsonschemajsonschema2pojo

How to show that each key of an object will have the same type?


I have a JSON response that return various metrics as values of and confidence that I would like represent as a JSON Schema (as well generating beans from using JsonSchema2Pojo).

{
    "QPI": {
        "value": 0.053916827852998075,
        "confidence": 0.89127
    },
    "MTBF": {
        "value": 0.053916827852998075,
        "confidence": 0.90210
    },
    "MDT": {
        "value": 0.053916827852998075,
        "confidence": 0.63541
    }
}

The number of metrics in the response is not fixed so I cannot represent them as properties.

If the response had been

[
    {
        "metric": "QPI",
        "value": 0.053916827852998075,
        "confidence": 0.89127
    },
    {
        "metric": "MTBF",
        "value": 0.053916827852998075,
        "confidence": 0.90210
    }, 

    {
        "metric": "MDT",
        "value": 0.053916827852998075,
        "confidence": 0.63541
    }
]

then I could write a schema like

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "metric": {
                "type": "string"
            },
            "value": {
                "type": "number"
            },
            "confidence": {
                "type": "number"
            }
        }
    }
}

but how to do it for the values of an object?


Solution

  • The "additionalProperties" is not just a boolean as in the case of "additionalProperties": false but can also take the type of object that is expected:

    {
        "type": "object",
        "additionalProperties": {
            "type": "object",
            "properties": {
                "value": {
                    "type": "number"
                },
                "confidence": {
                    "type": "number"
                }
            }
        }
    }