Json模式验证复杂结构

时间:2015-04-08 19:53:42

标签: json jsonschema

您好我需要帮助生成一个json架构来验证表单,下面的示例是一个成员数组,有很多成员类型,类型1是

项目经理,类型2系统分析员和类型3是开发人员。如果项目包含成员列表,我需要验证: 类型1的最小值1和最大值1; 2型最小1最多2; 最少2个最多2个类型3。

 {
"members": [
    {
        "memberid": 1,
        "membername": "John",
        "type": 1
    },
    {
        "memberid": 2,
        "membername": "Jack",
        "type": 2
    },
    {
        "memberid": 3,
        "membername": "Peter",
        "type": 3
    },
    {
        "memberid": 4,
        "membername": "Jorge",
        "type": 3
    },
    {
        "memberid": 5,
        "membername": "Clay",
        "type": 3
    }
]

}

1 个答案:

答案 0 :(得分:0)

这是一个艰难的。该解决方案的唯一限制是它要求成员按特定顺序排列。此外,如果将来需要其他组合,架构可能会失控。

{
  "type": "object",
  "properties": {
    "members": { "$ref": "#/definitions/members" }
  },
  "definitions": {
    "members": {
      "oneOf": [
        { "$ref": "#/definitions/smallTeam" },
        { "$ref": "#/definitions/largeTeam" }
      ]
    },
    "smallTeam": {
      "type": "array",
      "items": [
        { "$ref": "#/definitions/projectManager" },
        { "$ref": "#/definitions/systemAnalyst" },
        { "$ref": "#/definitions/developer" },
        { "$ref": "#/definitions/developer" }
      ],
      "additionalItems": false
    },
    "largeTeam": {
      "type": "array",
      "items": [
        { "$ref": "#/definitions/projectManager" },
        { "$ref": "#/definitions/systemAnalyst" },
        { "$ref": "#/definitions/systemAnalyst" },
        { "$ref": "#/definitions/developer" },
        { "$ref": "#/definitions/developer" }
      ],
      "additionalItems": false
    },
    "projectManager": {
      "type": "object",
      "allOf": [{ "$ref": "#/definitions/member" }],
      "properties": {
        "type": { "enum": [1] }
      }
    },
    "systemAnalyst": {
      "type": "object",
      "allOf": [{ "$ref": "#/definitions/member" }],
      "properties": {
        "type": { "enum": [2] }
      }
    },
    "developer": {
      "type": "object",
      "allOf": [{ "$ref": "#/definitions/member" }],
      "properties": {
        "type": { "enum": [3] }
      }
    },
    "member": {
      "type": "object",
      "properties": {
        "memberid": { "type": "integer" },
        "membername": { "type": "string" }
      },
      "required": ["memberid", "membername", "type"]
    }
  }
}

你能掌控这个结构吗?如果它有点不同,那么描述会容易得多。

{
  "type": "object",
  "properties": {
    "projectManager": { "$ref": "#/definitions/member" },
    "systemAnalyst": {
      "type": "array",
      "items": { "$ref": "#/definitions/member" },
      "minItems": 1,
      "maxItems": 2
    },
    "developer": {
      "type": "array",
      "items": { "$ref": "#/definitions/member" },
      "minItems": 1,
      "maxItems": 2
    }
  },
  "definitions": {
    "member": {
      "type": "object",
      "properties": {
        "memberid": { "type": "integer" },
        "membername": { "type": "string" }
      }
    }
  }
}