【问题标题】:Validate json schema of a particular JSON object from a response从响应中验证特定 JSON 对象的 json 模式
【发布时间】:2018-04-03 04:38:10
【问题描述】:

我有一个这样的 json 响应(响应是 com.jayway.restassured.response.Response 格式)。

[{
        gameIdGlobal: 1947634,
        season: 2017,
        views: [{
                name: "Recap",
                displayOrder: 1,
                groups: [{
                        type: "static",
                        displayOrder: 1
                    }
                ],
                localizedName: {
                    ENG: "Recap",
                    ESP: "Resumen"
                }
            }
        ]
    }
]

从这里我只需要验证视图对象的 json 模式。不需要验证整个 json 。为了那个原因 我已经为仅视图对象 schema1 创建了一个 json 架构。

schema1.json

{
    "type": "array",
    "items": {
        "id": "view.json",
        "type": "object",
        "properties": {
            "name": {
                "type": "string"
            },
            "displayOrder": {
                "type": "integer",
                "minimum": 1
            },
            "groups": {
                "type": "array"             
            },
            "localizedName": {
                "type": "object",
                "properties": {
                    "ENG": {
                        "type": "string",
                        "description": "the name of the view in english"
                    },
                    "ESP": {
                        "type": "string",
                        "description": "the name of the view in spanish"
                    }
                }
            }
        }
    }
}

如何执行特定 json 对象的架构验证(从 josn 响应查看对象)

代码

Response response = RestAssured.given().when().get(getURL);
 ValidatableResponse valResponse = response.then().contentType(ContentType.JSON);
  valResponse.body(schema1.json("schema1.json")).assertThat();

【问题讨论】:

    标签: java json jsonschema rest-assured rest-assured-jsonpath


    【解决方案1】:

    您可以指定在将数组作为其属性的对象上允许附加属性。这是整个响应 json 对象的架构:

    {
        "$schema": "http://json-schema.org/draft-06/schema#",
        "type": "array",
        "items": {
            "type": "object",
            "required": ["views"],
            "additionalProperties": true,
            "properties": {
                "views": {
                    "type": "array",
                    "items": {
                        "id": "view.json",
                      ...
            }
        }
    }
    

    【讨论】:

    • 那意味着只需要修改 josn 架构对吗?
    • 我们不必对代码进行任何修改。你能澄清一下吗
    • 是的。仅修改 json 架构。答案中的架构是针对问题中的响应量身定制的(这意味着响应是一个包含对象的数组,views 是一个项目的属性)您可能必须使用架构来适应结构
    • 好的。我也可以传递整个响应主体来验证特定的视图对象。不需要只提取视图对象响应..对吗?
    • 除此之外..您能否推荐一个好的模式生成器工具。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2022-10-16
    相关资源
    最近更新 更多