schema校验一个schema对应多个数据

oneOf,dependencies语法解决shcema校验中的多数据问题

最近在项目中遇到了schema校验问题,json数据中字段的输入情况是动态的,即一个接口需要满足两种数据格式,而这两份数据只有个别字段不一致,但是只能用一个schema文件进行校验,问题来了,如何用一个schema文件校验两个数据呢
下面的数据中,outHospitalNum与inHospitalNum为互斥关系,即只能存在一个,于是我采用了oneOf的方法进行了定义。定义key而不是value的类型需要用到关键字required
schema示例:

{
	"definitions": {},
	"type": "object",
	"required": [],
	"properties": {
		"count": {
			"oneOf": [{
			  "required": "number"
			},
			{
			  "minimum": 20
			}]
		}
	}
}

有且仅有一种情况满足时才能通过
而一般情况下,要用一个schema校验两个数据,必定伴生着某些必须字段,如果都用oneOf反而会很麻烦,于是dependencies登场了。

{
  "definitions": {
    "diseaseList": {
      "type": "string"
    },
    "inHospitalNum": {
      "type": "string"
    },
    "outHospitalNum": {
      "type": "string"
    }
  },
  "dependencies": {
    "inHospitalNum": [
      "A",
      "B",
      "C"
    ],
    "outHospitalNum": [
      "D",
      "E",
      "F"
    ],
    "A": [
      "inHospitalNum"
    ],
    "B": [
      "inHospitalNum"
    ],
    "C": [
      "inHospitalNum"
    ],
    "D": [
      "outHospitalNum"
    ],
    "E": [
      "outHospitalNum"
    ],
    "F": [
      "outHospitalNum"
    ]
  },
  "required": [
    "code"
  ],
  "properties": {
      "code": {
          "type": "string"
        },
    "inHospitalNum": {
      "$ref": "#/definitions/inHospitalNum"
    },
    "outHospitalNum": {
      "$ref": "#/definitions/outHospitalNum"
    },
    "A": {
      "type": "string"
    },
    "B": {
      "type": "string"
    },
    "C": {
      "type": "number"
    },
    "D": {
      "type": "string"
    },
    "E": {
      "type": "string"
    },
    "F": {
      "type": "number"
    }
  },
  "oneOf": [
    {
      "required": [
        "outHospitalNum"
      ]
    },
    {
      "required": [
        "inHospitalNum"
      ]
    }
  ]
}

如代码中所示,dependencies将与之相关的字段相联系,假如A存在,B,C,D中任意一个不存在,则无法通过,这种硬连接满足了我们对数据校验的要求。

发布了3 篇原创文章 · 获赞 0 · 访问量 47
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览