如何在JSON模式中使用定义(草案04) [英] How to use definitions in JSON schema (draft-04)

查看:105
本文介绍了如何在JSON模式中使用定义(草案04)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的其余服务响应类似于以下示例,这里我仅包括3个字段,但还有更多字段:

The rest service response I am working with is similar to following example, I have only included 3 fields here but there are many more:

{
    "results": [
        {
            "type": "Person",
            "name": "Mr Bean",
            "dateOfBirth": "14 Dec 1981"
        },
        {
            "type": "Company",
            "name": "Pi",
            "tradingName": "Pi Engineering Limited"
        }
    ]
}

我想为上述代码(草案04)编写一个JSON模式文件,该文件将明确指定以下内容:

I want to write a JSON schema file for above (draft-04) which will explicitly specify that:

if type == Person then list of required properties is ["type", "name", "dateOfBirth", etc] 
OR
if type == "Company" then list of required properties is ["type", "name", "tradingName", etc]

但是找不到任何文档或操作示例.

However am unable to find any documentation or example of how to do it.

目前,我的JSON模式如下:

Currently my JSON schema looks like following:

{
    "$schema": "http://json-schema.org/draft-04/schema",
    "type": "object",
    "required": ["results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["type", "name"],
                "properties": {
                    "type": { "type": "string" },
                    "name": { "type": "string" },
                    "dateOfBirth": { "type": "string" },
                    "tradingName": { "type": "string" }
                }
            }
        }
    }
}

有关如何处理此问题的任何指针/示例.

Any pointers/examples of how I should handle this.

推荐答案

我认为推荐的方法是

I think the recommended approach is the one shown in Json-Schema web, Example2. You need to use an enum to select schemas "by value". In your case it would be something like:

{
    "type": "object",
    "required": [ "results" ],
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "oneOf": [
                    { "$ref": "#/definitions/person" },
                    { "$ref": "#/definitions/company" }
                ]
            }
        }
    },
    "definitions": {
        "person": {
            "properties": {
                "type": { "enum": [ "person" ] },
                "name": {"type": "string" },
                "dateOfBirth": {"type":"string"}
            },
            "required": [ "type", "name", "dateOfBirth" ],
            "additionalProperties": false
        },
        "company": {
            "properties": {
                "type": { "enum": [ "company" ] },
                . . . 
            }        
        }
    }
}

这篇关于如何在JSON模式中使用定义(草案04)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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