JSON架构中的xsi:type相等 [英] Equal of xsi:type in JSON Schema

查看:102
本文介绍了JSON架构中的xsi:type相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 JSON架构中提示嵌入对象的类型 ,类似于XML模式中的xsi:type?

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

示例架构文档:

{
    "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).

推荐答案

JSON-schema AFAIK中没有与xsi:type等效的内容. 提示类型存在的最常见的JSON-schema方式可能是将类型明确定义为模式,并通过$ref引用它们:

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"]
        }
     }
   }

最后,您还可以将可以处理的任何标签添加到JSON-schema并遵循约定.

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

请注意,您将不会在典型的面向对象的编程语言(javaC#)继承语义和JSON-schema之间找到等效的翻译.

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.

这篇关于JSON架构中的xsi:type相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆