Equal of xsi:type in JSON Schema

久未见 提交于 2019-12-13 04:46:16

问题


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:


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.



来源:https://stackoverflow.com/questions/33627344/equal-of-xsitype-in-json-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!