1

使用json-schema-validator API v4 时出现错误。我试着做:

final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);

但每次我得到一个错误:# [schema]: unknown keyword contacts

schema.json :
{
    "contacts": {
        "description": "The list of contacts",
        "type": "array",
        "optional": true,
        "items": {
            "description": "A contact",
            "type": "object",
            "properties": {
                "givenName": {
                    "description": "Person's first name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                },
                "familyName": {
                    "description": "A person's last name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                }
            }
        }
    }
}

问候

4

2 回答 2

1

据我所知,您的数据看起来像这样-> json_data={"contacts":array}。如果这是真的,基本上你最外面的东西是一个对象(基本上是完整的 json 对象本身),你“可能”需要从你的 json as-> schema.json 的“顶级根”开始定义模式:

{
"description": "the outer json",
        "type": "object",
        "properties": {
            "contacts": {
                          "description": "The list of contacts",
                          "type": "array",
                          "optional": true,
                          "items": {
                                     "description": "A contact",
                                     "type": "object",
                                     "properties": {
                                     "givenName": {

etc.....

原谅我粗略的压痕。另外,我还没有测试过,请看看它是否有效,如果没有,我建议您提供您的 json_data (至少是示例)和 API 的示例,以便可以尝试找出问题所在。

于 2012-12-03T13:24:52.010 回答
0

使用 AVJ。无需将数据验证和清理逻辑编写为冗长的代码,您可以使用简洁、易于阅读和跨平台的 JSON Schema 或 JSON 类型定义规范声明对数据的要求,并在数据到达您的应用。

// validationSchema.js

import Ajv from "ajv";
import addFormats from "ajv-formats";
import ajvErrors from "ajv-errors";

const schemas = {
  newUser: {
    {
      type: "object",
      properties: {
        lastName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        firstName: {
          type: "string",
          minLength: 1,
          maxLength: 255
        },
        description: {
          type: "string"
        },
        birthday: {
          type: "string",
          format: "date-time"
        },
        status: {
          type: "string",
          enum: ["ACTIVE", "DELETED"]
        },
      },
      required: ["name"]
    }
  }
};

const ajv = new Ajv({ allErrors: true });

addFormats(ajv);
ajvErrors(ajv /*, {singleError: true} */);

const mapErrors = (errorsEntry = []) => {
  const errors = errorsEntry.reduce(
    (
      acc,
      { instancePath = "", message = "", params: { missingProperty = "" } = {} }
    ) => {
      const key = (instancePath || missingProperty).replace("/", "");

      if (!acc[key]) {
        acc[key] = [];
      }

      acc[key].push(`${key} ${message}`);

      return acc;
    },
    []
  );

  return errors;
};

const validate = (schemaName, data) => {
  const v = ajv.compile(schemas[schemaName]);
  let valid = false,
    errors = [];

  valid = v(data);
  if (!valid) {
    errors = mapErrors(v.errors);
  }

  return { valid, errors };
};

export default { validate };

您可以像这样验证它:

import validationSchema from "your_path/validationSchema.js"

const user = {
  firstName: "",
  lastName: "",
  ....
};

const { valid, errors = [] } = validationSchema.validate("newUser", user);

if(valid){
  console.log("Data is valid!");
} else {
  console.log("Data is not valid!");
  console.log(errors);
}

于 2022-02-13T21:16:22.040 回答