Equal of xsi:type in JSON Schema

2019-09-19 06:06发布

How can I hint the type of embedded objects in JSON Schema, analogous to xsi:type in XML Schema?

Example schema document:

{
    "type": "storeRequest",
    "properties": {
        "txid": {
            "description": "Transaction ID to prevent double committing",
            "type": "integer"
        },
        "objects": {
            "description": "Objects to store",
            "type": "array"
            "items": {
                "type": "object"
            },
            "minItems": 1,
            "uniqueItems": true
        },
    },
    "required": ["txid", "objects"]
}

This is a request the client sends to the server to store multiple objects in the database. Now how can I recursively validate the content of objects when it can contain more than one type of object. (Plymorphism, really).

1条回答
狗以群分
2楼-- · 2019-09-19 06:25

There is not an equivalent to xsi:type in JSON-schema AFAIK. Perhaps the most JSON-schema idiomatic way to hint the existence of types would be the explicit definition of types as schemas and referencing them through $ref:

{
    "properties" : {
        "wheels" : {
            "type" : "array",
            "items" : "$ref" : "#/definitions/wheel"
        }
    }

    "definitions" : {
        "wheel" : {
            "type" : "object"
        }
    }
}

Another way could be to give a hint through enums :

    {
    "definitions" : {
        "vehicle" : {
            "properties" : {
                "type" : {
                    "enum" : ["car", "bike", "plane"]
                }
            }
        },
        "plane" : {
            "properties" : {
                "type" : {
                    "enum" : "plane"
                }
            }
            "allOf" : ["$ref" : "#/definitions/vehicle"]
        }
     }
   }

Finally you can also add whatever tag you can process to a JSON-schema and follow your conventions.

Be aware that you are not going to find an equivalent translation between typical object oriented programming languages (java, C#) inheritance semantics and JSON-schema.

查看更多
登录 后发表回答