Создать структуру JSON Schema - PullRequest
0 голосов
/ 23 марта 2019

Как я могу преобразовать следующий объект в правильную схему JSON? Мне это нужно при реализации инструмента, который использует с уверенностью .

{
  "page": 2,
  "per_page": 3,
  "total": 12,
  "total_pages": 4,
  "data": [{
      "id": 4,
      "first_name": "Eve",
      "last_name": "Holt",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
    },
    {
      "id": 5,
      "first_name": "Charles",
      "last_name": "Morris",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
    },
    {
      "id": 6,
      "first_name": "Tracey",
      "last_name": "Ramos",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
    }
  ]
}

1 Ответ

0 голосов
/ 27 марта 2019

Вот ссылка, по которой вы можете создавать схемы JSON Schema Draft V4 онлайн

JSON Schema Generator Online

Вот сгенерированная схема JSON. Вы можете изменить необходимый блок в зависимости от ваших требований

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "page": {
      "type": "integer"
    },
    "per_page": {
      "type": "integer"
    },
    "total": {
      "type": "integer"
    },
    "total_pages": {
      "type": "integer"
    },
    "data": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "id": {
              "type": "integer"
            },
            "first_name": {
              "type": "string"
            },
            "last_name": {
              "type": "string"
            },
            "avatar": {
              "type": "string"
            }
          },
          "required": [
            "id",
            "first_name",
            "last_name",
            "avatar"
          ]
        }
      ]
    }
  },
  "required": [
    "page",
    "per_page",
    "total",
    "total_pages",
    "data"
  ]
}

Если у вас есть JSON и схема, вы можете проверить, используя уверенность в следующем:

@Test(enabled=true)
    public void schemaValidation() {

            RestAssured.given().get("http://localhost:8080/endpoint")
                    .then().assertThat().body(matchesJsonSchemaInClasspath(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"JsonSchemas"+File.separator+"SampleSchema.json"));

    }

Или у вас есть пользовательская проверка, как показано ниже

@Test(enabled=true)
    public void schemaValidation2() throws IOException, ProcessingException {

           Response response =  RestAssured.given().get("http://localhost:8080/endpoint")
                    .andReturn();

           com.github.fge.jsonschema.main.JsonSchema schemaFileJson = ValidationUtils.getSchemaNode(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"JsonSchemas"+File.separator+"SampleSchema.json");
            ObjectMapper mapper = new ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode responseBodyJsonObject = mapper.readTree(response.getBody().asString());


            if(schemaFileJson.validate(responseBodyJsonObject).isSuccess()) {
                System.out.println("Schema is valid");
            }else {
                System.out.println("Schema is not valid");
            }

    }

Зависимости Maven

<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>
        <dependency>
            <groupId>com.github.fge</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>2.2.6</version>
        </dependency>
        <dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>3.0.0</version>
</dependency>
        <!-- https://mvnrepository.com/artifact/com.github.fge/jackson-coreutils -->
        <dependency>
            <groupId>com.github.fge</groupId>
            <artifactId>jackson-coreutils</artifactId>
            <version>1.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.fge/json-schema-core -->
        <dependency>
            <groupId>com.github.fge</groupId>
            <artifactId>json-schema-core</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
        </dependency>
...