可以通过引用类型来声明您的JSON模式吗?

时间:2016-10-26 14:31:17

标签: java jsonschema json-schema-validator

我正在尝试验证一小部分JSON,如:

<PlatformToolset>v140</PlatformToolset>

适用于架构:

{
    "success": true,
    "message": "all's good!"
}

然而它失败了架构

{
    "type": "object",
    "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
    }
}

错误

  

java.lang.AssertionError:架构资源:/json-schema/sample.schema.json是&gt;无效:致命:JSON架构无效,无法继续   语法错误:

{
    "definitions": {
        "response": {
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "message": { "type": "string"  }
            }
        }
    },

    "type": { "$ref": "#/definitions/response" }
}
  

级别:“致命”

您是否不允许在定义部分之外使用类型的引用?我的动机是这是对一个单一案例的回应,但有些情况下这个结构也嵌套在其他案例中。

如果重要,我正在使用json-schema-validator版本2.2.6。

PS - 这是一个简化的例子,实际的架构更加复杂,以证明为什么需要重用而不是复制和粘贴。

3 个答案:

答案 0 :(得分:1)

您可以使用“id”和“$ ref”。

用于识别的ID,例如:

{
    "type": "object",
      "id": "#response",
      "properties": {
        "success": { "type": "boolean" },
        "message": { "type": "string"  }
       }
  }
}

然后你使用$ ref,例如:

"some": { "$ref": "#response" }

或外部参考:

"ext": { "$ref": "http://url.com#response" }

请参阅 http://json-schema.org/latest/json-schema-core.html#anchor27

答案 1 :(得分:1)

type关键字的值必须是其中一个JSON原始类型的名称字符串(例如&#34;字符串&#34;,&#34;数组&#34;等) ,或这些字符串的数组。这就是错误信息所说的内容。关键字type必须是字符串或数组。与我认为你想要做的最接近的是......

{
    "definitions": {
        "response": {
            "type": "object",
            "properties": {
                "success": { "type": "boolean" },
                "message": { "type": "string"  }
            }
        }
    },
    "allOf": [{ "$ref": "#/definitions/response" }]
}

答案 2 :(得分:0)

您应该在自己的文件中声明您的定义,并且它们的类型引用该文件引用。有关详细信息,请参阅How to manage multiple JSON schema files?