Будьте уверены, JSON-схема-валидатор

Я использую валидатор схемы json с уверенностью, это моя схема:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://jsonschema.net#",
  "type": "object",
  "required": false,
  "properties": {
    "id": {
      "id": "http://jsonschema.net/id#",
      "type": "object",
      "required": false,
      "properties": {
        "keyVal": {
          "id": "http://jsonschema.net/id/keyVal#",
          "type": "string",
          "required": false
        }
      }
    },
    "name": {
      "id": "http://jsonschema.net/name#",
      "type": "string",
      "required": false
    },
    "description": {
      "id": "http://jsonschema.net/description#",
      "type": "string",
      "required": false
    },
    "updatedBy": {
      "id": "http://jsonschema.net/updatedBy#",
      "type": "string",
      "required": false
    },
    "dateModified": {
      "id": "http://jsonschema.net/dateModified#",
      "type": "integer",
      "required": false
    },
    "arePhrasesCaseSensitive": {
      "id": "http://jsonschema.net/arePhrasesCaseSensitive#",
      "type": "boolean",
      "required": false
    },
    "phrasesList": {
      "id": "http://jsonschema.net/phrasesList#",
      "type": "array",
      "required": false,
      "items": [
        {
          "id": "http://jsonschema.net/phrasesList/0#",
          "type": "object",
          "required": false,
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/0/value#",
              "type": "string",
              "required": false
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/0/weight#",
              "type": "string",
              "required": false
            }
          }
        },
        {
          "id": "http://jsonschema.net/phrasesList/1#",
          "type": "object",
          "required": false,
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/1/value#",
              "type": "string",
              "required": false
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/1/weight#",
              "type": "string",
              "required": false
            }
          }
        },
        {
          "id": "http://jsonschema.net/phrasesList/2#",
          "type": "object",
          "required": false,
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/2/value#",
              "type": "string",
              "required": false
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/2/weight#",
              "type": "string",
              "required": false
            }
          }
        }
      ]
    }
  }
}

а это мой JSON:

{
"id": {
"keyVal": "jkl3"
},
"name": "name",
"description": "description",
"type": "TYPE",
"updatedBy": "updatedBy",
"dateModified": 1398845197348,
"arePhrasesCaseSensitive": false
}

Я использую juint для тестирования с помощью assert:

json = SimpleFileReader.getFileAsString("my.json");

assertThat(json, matchesJsonSchemaInClasspath("products-schema.json"));

моя версия json-schema-validator: 2.3.1

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>2.3.1</version>
</dependency>

Что мне не хватает?

Это полная ошибка:

com.jayway.restassured.module.jsv.JsonSchemaValidationException: com.github.fge.jsonschema.core.exceptions.InvalidSchemaException: fatal: core.invalidSchema
    level: "fatal"

    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:223)
    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:75)
    at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
    at org.junit.Assert.assertThat(Assert.java:772)
    at org.junit.Assert.assertThat(Assert.java:738)
    at com.websense.rest.assured.RestTestBase.testGetList(RestTestBase.java:56)
    at com.websense.rest.assured.TestSample.testList(TestSample.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.github.fge.jsonschema.core.exceptions.InvalidSchemaException: fatal: core.invalidSchema
    level: "fatal"

    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:86)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:48)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.main.JsonSchema.doValidate(JsonSchema.java:75)
    at com.github.fge.jsonschema.main.JsonSchema.validate(JsonSchema.java:108)
    at com.github.fge.jsonschema.main.JsonSchema.validate(JsonSchema.java:124)
    at com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesSafely(JsonSchemaValidator.java:217)
    ... 30 more

person Michael Biniashvili    schedule 05.05.2014    source источник


Ответы (1)


(здесь автор - часть json-schema-validator) Ваша схема действительно недействительна. Ключевое слово "required" так вообще не используется.

К сожалению, у вас нет сообщений об ошибках, связанных со схемой, вы можете попробовать вставить ее сюда, чтобы увидеть ошибку.

Вы пытаетесь использовать required, как это было определено в основном в проекте v3, и требуемый «верхний уровень» в любом случае не имеет смысла. Вы хотите, чтобы это было схемой:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://jsonschema.net#",
  "type": "object",
  "properties": {
    "id": {
      "id": "http://jsonschema.net/id#",
      "type": "object",
      "properties": {
        "keyVal": {
          "id": "http://jsonschema.net/id/keyVal#",
          "type": "string"
        }
      }
    },
    "name": {
      "id": "http://jsonschema.net/name#",
      "type": "string"
    },
    "description": {
      "id": "http://jsonschema.net/description#",
      "type": "string"
    },
    "updatedBy": {
      "id": "http://jsonschema.net/updatedBy#",
      "type": "string"
    },
    "dateModified": {
      "id": "http://jsonschema.net/dateModified#",
      "type": "integer"
    },
    "arePhrasesCaseSensitive": {
      "id": "http://jsonschema.net/arePhrasesCaseSensitive#",
      "type": "boolean"
    },
    "phrasesList": {
      "id": "http://jsonschema.net/phrasesList#",
      "type": "array",
      "items": [
        {
          "id": "http://jsonschema.net/phrasesList/0#",
          "type": "object"
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/0/value#",
              "type": "string"
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/0/weight#",
              "type": "string"
            }
          }
        },
        {
          "id": "http://jsonschema.net/phrasesList/1#",
          "type": "object"
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/1/value#",
              "type": "string"
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/1/weight#",
              "type": "string"
            }
          }
        },
        {
          "id": "http://jsonschema.net/phrasesList/2#",
          "type": "object"
          "properties": {
            "value": {
              "id": "http://jsonschema.net/phrasesList/2/value#",
              "type": "string"
            },
            "weight": {
              "id": "http://jsonschema.net/phrasesList/2/weight#",
              "type": "string"
            }
          }
        }
      ]
    }
  }
}

По сути, ваша схема больше не требует "обязательного". Обратите внимание, что по умолчанию присутствие членов объекта не требуется; они будут проверены, только если они присутствуют в данных.

Если вы хотите, чтобы, скажем, члены «foo» и «bar» присутствовали в объекте JSON, вы должны написать следующее:

{
    "type": "object",
    "required": [ "foo", "bar" ],
    "etc": "etc"
}
person fge    schedule 06.05.2014
comment
Я обновляю схему, как вы меня просите, и я все еще получаю сообщение об ошибке, я обнаружил, что если я удалю ключи: id и type из моего json, он будет работать. {name: name, description: description, updatedBy: updatedBy, dateModified: 1398845197348, arePhrasesCaseSensitive: false,} похоже, что мы не можем использовать слова: id и ввести json. - person Michael Biniashvili; 07.05.2014
comment
Что ж, полученная вами ошибка не совсем информативна; Я предлагаю вам попробовать и использовать этот сайт для анализа / исправления вашей схемы и данных. - person fge; 07.05.2014
comment
согласно этому сайту моя схема и JSON действительны. - person Michael Biniashvili; 07.05.2014
comment
Но уверенный модуль не согласен? Значит, это похоже на ошибку в этом модуле; не могли бы вы вставить полную трассировку стека (в вопрос, а не в комментарий)? - person fge; 07.05.2014
comment
Я обновляю вопрос, чтобы включить полную ошибку, я могу отправить вам образец проекта с ошибкой, если хотите. - person Michael Biniashvili; 07.05.2014