当前位置: 首页 > 知识库问答 >
问题:

使用放心,我如何验证Json对象数组中的数据类型

宋伟泽
2023-03-14

我是新手,尝试使用json模式验证器版本4.3.0进行一些验证。运行时会出错。在这方面需要帮助。

这是我的模式(sample.json):

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "title": {
      "type": "string"
    },
    "subTitle": {
      "type": "string"
    },
    "author": {
      "type": "string"
    },
    "publish_date": {
      "type": "string"
    },
    "publisher": {
      "type": "string"
    },
    "pages": {
      "type": "number"
    },
    "Description": {
      "type": "string"
    },
    "Website": {
      "type": "string"
    }
  },
  "required": ["title", "subTitle", "author", "publish_date", "publisher", "pages", "Description", "Website"]
}

我的json响应是这样的:

{
  "books": [
    {
      "isbn": "9781449325862",
      "title": "Git Pocket Guide",
      "subTitle": "A Working Introduction",
      "author": "Richard E. Silverman",
      "publish_date": "2020-06-04T08:48:39.000Z",
      "publisher": "O'Reilly Media",
      "pages": 234,
      "description": "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git exp",
      "website": "http://chimera.labs.oreilly.com/books/1230000000561/index.html"
    }
}

编写的测试用例是:

public class AppTest {
 
    @Test
    public void verifyJsonSchema() {
        

        // GIVEN
        RestAssured
            .given()
                .baseUri("https://bookstore.toolsqa.com/BookStore/v1/Books/9781449325862")
        // WHEN
            .when()
                .get()
        // THEN
            .then()
                .assertThat()
                .statusCode(200)
                .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("sample.json"));
    }
 
}

我/我得到的错误是:

[RemoteTestNG] detected TestNG version 6.14.3
FAILED: verifyJsonSchema
io.restassured.module.jsv.JsonSchemaValidationException: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@56febdc; line: 2, column: 2]
    at io.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:233)
    at io.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:75)
    at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
    at org.hamcrest.Matcher$matches.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at io.restassured.assertion.BodyMatcher.validate(BodyMatcher.groovy:76)
    at io.restassured.assertion.BodyMatcher$validate$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:144)
    at io.restassured.assertion.BodyMatcherGroup$_validate_closure2.doCall(BodyMatcherGroup.groovy:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
    at groovy.lang.Closure.call(Closure.java:418)
    at groovy.lang.Closure.call(Closure.java:434)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.collect(DefaultGroovyMethods.java:3287)
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.collect(DefaultGroovyMethods.java:3257)
    at org.codehaus.groovy.runtime.dgm$67.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:274)
    at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at io.restassured.assertion.BodyMatcherGroup.validate(BodyMatcherGroup.groovy:47)
    at io.restassured.assertion.BodyMatcherGroup$validate$3.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:144)
    at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:481)
    at io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
    at io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:656)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
    at io.restassured.internal.ResponseSpecificationImpl.content(ResponseSpecificationImpl.groovy:97)
    at io.restassured.specification.ResponseSpecification$content$1.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:177)
    at io.restassured.internal.ResponseSpecificationImpl.body(ResponseSpecificationImpl.groovy:256)
    at io.restassured.internal.ValidatableResponseOptionsImpl.body(ValidatableResponseOptionsImpl.java:268)
    at Sample.Sample.AppTest.verifyJsonSchema(AppTest.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@56febdc; line: 2, column: 2]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1369)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:532)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:453)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleUnexpectedValue(ReaderBasedJsonParser.java:1386)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:669)
    at com.fasterxml.jackson.databind.MappingIterator.hasNextValue(MappingIterator.java:159)
    at com.github.fge.jackson.JsonNodeReader.readNode(JsonNodeReader.java:142)
    at com.github.fge.jackson.JsonNodeReader.fromReader(JsonNodeReader.java:127)
    at com.github.fge.jackson.JsonLoader.fromReader(JsonLoader.java:193)
    at com.github.fge.jackson.JsonLoader.fromString(JsonLoader.java:206)
    at io.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:214)
    ... 80 more

此外,我想知道是否有可能验证不同的数据类型,如字符,日期,数字?如果是的话,那也帮我一下。

提前感谢...

共有1个答案

郑松
2023-03-14

您的模式是错误的。您可以使用这个模式。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "books": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "isbn": {
              "type": "string"
            },
            "title": {
              "type": "string"
            },
            "subTitle": {
              "type": "string"
            },
            "author": {
              "type": "string"
            },
            "publish_date": {
              "type": "string"
            },
            "publisher": {
              "type": "string"
            },
            "pages": {
              "type": "integer"
            },
            "description": {
              "type": "string"
            },
            "website": {
              "type": "string"
            }
          },
          "required": [
            "isbn",
            "title",
            "subTitle",
            "author",
            "publish_date",
            "publisher",
            "pages",
            "description",
            "website"
          ]
        }
      ]
    }
  },
  "required": [
    "books"
  ]
}

在json中,有6种数据类型:数字、字符串、数组、对象、布尔和空。无法验证字符、日期和时间。。。

 类似资料:
  • 给定我有这个JSON数组: 我想使用Rest-assured使用它的给定/when/then结构来验证字段的格式。 我如何放心地循环并对JSON数组中的每个值应用测试? 我不知道JSON数组中会有多少个值。它可能只有1;它可能是100。

  • 问题内容: 我有一系列数据要输入数据库。输入数据的用户界面不适用于批量输入,因此我尝试制定等效的命令行。当我检查Chrome中UI的网络请求时,看到了json对象的PUT请求。当我尝试复制请求时 我得到一个错误 curl:(3)位置X不支持[globbing]嵌套括号 其中X是第一个“ [”的字符位置。 如何放置包含数组的json对象? 问题答案: 您的命令行应该在要发送到PUT中的字符串之前插入

  • 我正在尝试使用模式验证响应JSON。即使尝试使用错误的模式验证响应,测试用例也会通过。 JSON响应: JSON模式: 我预计这里会出现错误,因为响应不包含所需的served_imsi值。但考验正在通过。

  • 问题内容: 我使用sf.json库在Java Web应用程序中映射传入请求的表单数据。 可以说传入请求是http:// localhost:8080 / app / addProfile ,其表单数据为: 服务器端 : 这种方法的主要问题是,如果对结构进行少量修改,则需要修改整个代码。 有没有可以配置验证所需规则的api? 问题答案: 您可以使用Json验证器:-https: //github.c

  • 我使用sf.json库来映射在java中的Web应用程序中传入请求的表单数据。 假设传入请求http://localhost:8080/app/addProfile表单数据为: 服务器端: 这种方法的主要问题是,如果在结构中有微小的修改,那么整个代码都需要修改。 是否有api可以配置验证所需的规则?

  • 示例JSON 我想要一个数组[属性1,属性2] 如何使用est保证的JSON路径提取器实现?