jsonschema fge json-schema-validator 高级能力 自定义类校验

入参校验产品化 schema_个人渣记录仅为自己搜索用的博客-CSDN博客

自定义的string format可以使用. 详见 

  fpe的 addFormatValidator

 ajv 的 addFormat能力

借鉴自chatgpt, 谷歌了半天,没看到好答案.

Q: "jsonschema 自定义 object  校验"

A: 如下

2014年后未更新 

<dependency>
  <groupId>com.github.fge</groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>2.2.14</version>
</dependency>

 

创建自定义AbstractKeywordValidator

要自定义 JSON Schema 中的对象校验,您需要编写一个自定义验证器。以下是一个示例,它定义了一个名为“myObject”的自定义对象校验,该校验验证对象是否包含一个名为“foo”的属性:

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.core.util.Dictionary;
import com.github.fge.jsonschema.keyword.validator.AbstractKeywordValidator;

public class MyObjectValidator extends AbstractKeywordValidator {
    private static final Dictionary<String> messages = messages();

    public MyObjectValidator(final JsonNode digest) {
        super("myObject");
    }

    @Override
    public void validate(final ProcessingReport report, final JsonNode schema, final JsonNode instance) throws ProcessingException {
        if (!instance.has("foo")) {
            report.error(newMsg(schema, messages.get("err.object.noFoo")));
        }
    }
}

注册到 JSON Schema

然后,您需要将此验证器注册到 JSON Schema 中:

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonschema.core.load.configuration.LoadingConfiguration;
import com.github.fge.jsonschema.core.load.uri.URITranslatorConfiguration;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.core.report.ProcessingReportBuilder;
import com.github.fge.jsonschema.core.report.ReportProvider;
import com.github.fge.jsonschema.core.report.ReportProviderConfiguration;
import com.github.fge.jsonschema.core.report.ReportProviderFactory;
import com.github.fge.jsonschema.core.report.Slf4jLogLevel;
import com.github.fge.jsonschema.core.report.Slf4jReportProvider;
import com.github.fge.jsonschema.core.util.URIUtils;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import com.github.fge.jsonschema.main.JsonValidatorBuilder;
import com.github.fge.jsonschema.processors.syntax.SyntaxValidator;

public class MySchemaFactory {
    private static final JsonValidator VALIDATOR;
    private static final JsonSchemaFactory FACTORY;

    static {
        final ReportProviderConfiguration reportProviderConfiguration = new ReportProviderConfiguration()
                .setLogProvider(Slf4jReportProvider.provider())
                .setLogLevel(Slf4jLogLevel.DEBUG);
        final ReportProviderFactory reportProviderFactory = new ReportProviderFactory(reportProviderConfiguration);
        final ReportProvider reportProvider = reportProviderFactory.createReportProvider();
        final ProcessingReportBuilder reportBuilder = reportProvider.newReportBuilder();
        final LoadingConfiguration loadingConfiguration = LoadingConfiguration.newBuilder()
                .setURITranslatorConfiguration(URITranslatorConfiguration.newBuilder()
                        .setNamespace(URIUtils.toURI("http://example.com/schemas"))
                        .freeze())
                .freeze();
        final JsonValidatorBuilder validatorBuilder = JsonValidator.newBuilder()
                .setReportProvider(reportProvider)
                .setLoadingConfiguration(loadingConfiguration)
                .setSyntaxValidator(SyntaxValidator.none());
        VALIDATOR = validatorBuilder.build();
        FACTORY = JsonSchemaFactory.newBuilder()
                .setValidator(VALIDATOR)
                .addKeywordValidator("myObject", new MyObjectValidator(null))
                .freeze();
    }

    public static JsonSchema getSchema(final JsonNode schemaNode) throws ProcessingException {
        return FACTORY.getJsonSchema(schemaNode);
    }
}

校验

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class MyObjectValidatorTest {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Test
    public void testValid() throws ProcessingException {
        final JsonNode schemaNode = MAPPER.readTree("{\"type\": \"object\", \"myObject\": true}");
        final JsonSchema schema = MySchemaFactory.getSchema(schemaNode);
        assertTrue(schema.validate(MAPPER.readTree("{\"foo\": \"bar\"}")).isSuccess());
    }

    @Test
    public void testInvalid() throws ProcessingException {
        final JsonNode schemaNode = MAPPER.readTree("{\"type\": \"object\", \"myObject\": true}");
        final JsonSchema schema = MySchemaFactory.getSchema(schemaNode);
        assertFalse(schema.validate(MAPPER.readTree("{\"bar\": \"foo\"}")).isSuccess());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 Java 语言编写程序来校验 JSON Schema 是非常容易的,可以使用许多库和框架来帮助您实现它。有许多第三方库和框架可以用于校验 JSON 格式,这些库和框架包括:Jackson,Gson,Genson,Apache Commons,Hibernate ValidatorJsonSchemaJsonPath 和 FastJSON。 ### 回答2: 在Java中,可以使用现有的库来编写代码,使用jsonSchema校验数据。下面是使用Java编写的示例代码: 首先,需要导入相关的依赖库,例如使用Jackson库来处理JSON数据和使用json-schema-validator库来执行jsonSchema校验。可以通过Maven或Gradle等构建工具来管理依赖。 接下来,创建一个方法来执行校验操作。首先,需要定义jsonSchema的规则,可以使用JSON字符串或从外部文件中加载。然后,需要将待校验的数据转换为JSON对象,可以使用Jackson库将字符串解析为JSON对象。 然后,使用json-schema-validator库中的JsonSchemaFactory来创建JsonSchema实例。使用JsonSchemavalidate方法对JSON数据进行校验,该方法会返回校验结果。 最后,根据校验结果进行相应的处理,可以输出校验失败的原因或执行其他操作。 以下是一个简单的示例代码: ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; public class JsonValidator { public static void main(String[] args) { String schema = "{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } } }"; String data = "{ \"name\": \"John\" }"; boolean isValid = validateData(schema, data); if (isValid) { System.out.println("Data is valid."); } else { System.out.println("Data is invalid."); } } public static boolean validateData(String schemaString, String dataString) { ObjectMapper objectMapper = new ObjectMapper(); JsonNode schemaNode, dataNode; try { schemaNode = objectMapper.readTree(schemaString); dataNode = objectMapper.readTree(dataString); } catch (Exception e) { e.printStackTrace(); return false; } JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault(); try { JsonSchema schema = schemaFactory.getJsonSchema(schemaNode); ProcessingReport report = schema.validate(dataNode); return report.isSuccess(); } catch (ProcessingException e) { e.printStackTrace(); return false; } } } ``` 以上代码使用了Jackson库将schema和数据解析为JSON节点,然后使用json-schema-validator库来创建JsonSchema对象,并使用validate方法进行校验。最后根据校验结果输出相应的信息。 当运行以上代码时,如果数据满足schema的定义,会输出"Data is valid.",否则输出"Data is invalid."。这个示例中使用了简单的schema和数据进行校验,实际使用中可以根据需要定义更复杂的schema,并使用更复杂的校验逻辑。 ### 回答3: 使用Java编写可以使用以下步骤来使用jsonSchema校验数据。 首先,你需要引入json-schema-validator库。你可以在Maven或Gradle中添加以下依赖项: 对于Maven: ```xml <dependency> <groupId>org.everit.json</groupId> <artifactId>org.everit.json.schema</artifactId> <version>1.12.1</version> </dependency> ``` 对于Gradle: ```groovy implementation 'org.everit.json:org.everit.json.schema:1.12.1' ``` 接下来,你需要创建一个json schema的字符串或从文件中读取json schema。假设你有以下的json schema字符串: ```json String schemaStr = "{\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": {\n" + " \"type\": \"string\"\n" + " },\n" + " \"age\": {\n" + " \"type\": \"integer\"\n" + " }\n" + " },\n" + " \"required\": [\"name\", \"age\"]\n" + "}"; ``` 然后你可以使用下面的代码来校验数据: ```java import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; class Main { public static void main(String[] args) { String dataStr = "{\"name\":\"John\", \"age\":30}"; try { JSONObject jsonSchema = new JSONObject(new JSONTokener(schemaStr)); JSONObject jsonData = new JSONObject(new JSONTokener(dataStr)); Schema schema = SchemaLoader.load(jsonSchema); schema.validate(jsonData); System.out.println("数据是有效的"); } catch (ValidationException e) { System.out.println("数据无效:" + e.getMessage()); } } } ``` 以上代码将创建一个Schema对象,并使用Schema.validate方法来验证数据。如果数据有效,将输出“数据是有效的”,否则将输出"数据无效"及详细错误信息。 这就是使用Java编写jsonSchema校验数据的基本步骤。你可以根据自己的需求修改json schema和数据,并在代码中进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值