java校验方案选择

参数校验的方案

1. 简单参数校验,使用Guava的Preconditions。

参考:Guava学习笔记:Preconditions优雅的检验参数

2. Bean校验,使用Hibernate Validator

参考:Hibernate Validator The Bean Validation reference implementation.

3. Map,JSON校验,使用JSONSchema

参考:json-schema

 

JSONSchema校验的优点

1. JSONSchema是一种规范,是跨语言的。

2. 适用于以json对象交互的接口中。适应json数据变化多端的特性。

3. Java中对JSON对象校验的缺失,由JSONSchema来弥补

4. 让校验变得文档化,便于集中管理

 

Java操作JSONSchema的案例

1. maven中添加依赖



    com.github.fge
    json-schema-validator
    2.2.6

2. 编写jsonschema文档

{
    "$schema":"http://json-schema.org/draft-04/schema",
    "type":"object",
    "properties": {
        "name": {
            "type":"string"
        },
        
        "versions": {
            "type":"array",
            "items": {
                "type":"object",
                "properties": {
                    "id": {
                        "type":"string"
                    },
                    
                    "version": {
                        "type":"integer"
                    },
                    
                    "comment": {
                        "type":"string"
                    }
                },
                
                "required":["id", "version"],
                "minItems":1
            }
        }
    },
    
    "required":["name", "versions"]
}

3. java代码

import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
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 JsonShemaValidator {

    private static Log log = LogFactory.getLog(JsonShemaValidator.class);

    private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();

    /**
     * validate instance and Schema,here including two functions. as follows:
     * first: the Draft v4 will check the syntax both of schema and instance.
     * second: instance validation.
     * 
     * @param mainSchema
     * @param instance
     * @return
     * @throws IOException
     * @throws ProcessingException
     */
    public static ProcessingReport validatorSchema(String mainSchema, String instance) throws IOException, ProcessingException {
        JsonNode mainNode = JsonLoader.fromString(mainSchema);
        JsonNode instanceNode = JsonLoader.fromString(instance);
        JsonSchema schema = factory.getJsonSchema(mainNode);
        ProcessingReport processingReport = schema.validate(instanceNode);
        log.info(processingReport);

        return processingReport;
    }

}

 

参考:

总结一下最近用到的技术(2)--JsonSchema和JsonSchemaValidator

 

你可能感兴趣的:(java)