何为Json-Schema
Json-schema是描述你的JSON数据格式;JSON模式(应用程序/模式+ JSON)有多种用途,其中之一就是实例验证。验证过程可以是交互式或非交互式的。例如,应用程序可以使用JSON模式来构建用户界面使互动的内容生成除了用户输入检查或验证各种来源获取的数据。(来自百度百科)

相关jar包

<dependency>  <groupId>com.github.fge</groupId>  <artifactId>json-schema-validator</artifactId>  <version>2.2.6</version>
</dependency>
<!-- fasterxml -->
<dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-core</artifactId>  <version>2.3.0</version>
</dependency>
<dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-databind</artifactId>  <version>2.3.0</version>
</dependency>

package com.gaci;

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.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import org.apache.commons.lang.ArrayUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Iterator;

/**

  • Created by Gaci on 2020/8/3.
    */
    public class JSONSchemaUtil {
    // 创建订单请求JSON格式校验
    private static String schema;

    static {

     // 获取创建订单格式校验try {String str = "";
    

// String filePath = JSONSchemaUtil.class.getResource("/schema.json").getPath();// src目录下
// filePath = filePath.substring(1);
// InputStream in = new FileInputStream(new File(filePath));
InputStream in = new FileInputStream(new File(“E:\schema.json”));
BufferedReader reader = new BufferedReader(new InputStreamReader(in,“UTF-8”));
String line;
while ((line = reader.readLine()) != null) {
str += line;
}
schema = str;
// System.out.println(schema);
} catch (Exception e) {
e.printStackTrace();
}
}

private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();/*** 校验创建订单请求的格式* @param mainSchema* @param instance* @return* @throws IOException* @throws ProcessingException*/
//    public static ProcessingReport validatorSchema(String mainSchema, String instance) throws IOException, ProcessingException {
public static String validatorSchema(String mainSchema, String instance) throws IOException, ProcessingException {String error = "";JsonNode mainNode = JsonLoader.fromString(mainSchema);JsonNode instanceNode = JsonLoader.fromString(instance);

// com.fasterxml.jackson.databind.JsonNode mainNode = JsonLoader.fromString(mainSchema);
// com.fasterxml.jackson.databind.JsonNode instanceNode = JsonLoader.fromString(instance);

    JsonSchema schema = factory.getJsonSchema(mainNode);ProcessingReport processingReport = schema.validate(instanceNode);String s = processingReport.toString();boolean flag = processingReport.isSuccess();if(!flag){error = convertMessage(processingReport,mainNode);}return error;
}/****根据 report里面的错误字段,找到schema对应字段定义的中文提示,显示都前端* @param report 校验json 的结果,里面包含错误字段,错误信息。* @param schema 原始的schema文件。主要用来读取message,message中文信息*/
private static String  convertMessage(ProcessingReport report, JsonNode schema) {String error = "";Iterator<ProcessingMessage> iter = report.iterator();ProcessingMessage processingMessage = null;//保存校验失败字段的信息JsonNode schemaErrorFieldJson = null;//原始校验返回的信息JsonNode validateResult = null;while (iter.hasNext()) {processingMessage = iter.next();validateResult = processingMessage.asJson();//keyword表示 一定是不符合schema规范JsonNode keywordNode = validateResult.get("keyword");

// JsonNode nn = validateResult.get(“message”);
JsonNode in = validateResult.get(“instance”);
if (null != keywordNode) {
//说明json validate 失败
String keyword = keywordNode.textValue();

            schemaErrorFieldJson = findErrorField(schema, validateResult);//keyword 如果是require说明缺少必填字段,取schema中 字段对应的messageif ("required".equalsIgnoreCase(keyword)) {//如果是require,找到哪个字段缺少了JsonNode missingNode = null;if (null == schemaErrorFieldJson) {missingNode = validateResult.get("message");schemaErrorFieldJson = schema.get("properties").get(missingNode.get(0).textValue());}if (null != validateResult.get("message")) {

// Preconditions.checkArgument(false, validateResult.get(“message”).textValue());
// error += in.get(“pointer”).textValue()+":";
error += validateResult.get(“message”).textValue();
}
} else {
//非必填校验失败。说明是格式验证失败。取schema中 字段对应的message
if (null != validateResult.get(“message”)) {
// Preconditions.checkArgument(false, validateResult.get(“message”).textValue());
error += in.get(“pointer”).textValue()+":";
error += validateResult.get(“message”).textValue()+";";
}

            }}}

// System.out.println(error);
return error;
}

/**** 根据校验结果的 schema pointer 中的url递归寻找JsonNode* @param schema* @param validateResult* @return*/
private static JsonNode findErrorField(JsonNode schema, JsonNode validateResult) {//取到的数据是String[] split = validateResult.get("schema").get("pointer").textValue().split("/");JsonNode tempNode = null;if (!ArrayUtils.isEmpty(split)) {for (int i = 1; i < split.length; i++) {if (i == 1) {tempNode = read(schema, validateResult, split[i]);} else {tempNode = read(tempNode, validateResult, split[i]);}}}return tempNode;
}private static JsonNode read(JsonNode jsonNode, JsonNode validateResult, String fieldName) {return jsonNode.get(fieldName);
}//获取请求体中的数据

// public String getStrResponse(){
// ActionContext ctx = ActionContext.getContext();
// HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
// InputStream inputStream;
// String strResponse = “”;
// try {
// inputStream = request.getInputStream();
// String strMessage = “”;
// BufferedReader reader;
// reader = new BufferedReader(new InputStreamReader(inputStream,“utf-8”));
// while ((strMessage = reader.readLine()) != null) {
// strResponse += strMessage;
// }
// reader.close();
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return strResponse;
// }

public static void main(String[] args){try {String str = "{\"name\":\"123\",\"sex\":\"男\"}";String s = validatorSchema(schema, str);System.out.println(s);}catch (Exception e){e.printStackTrace();}}

}

schema.json

{"type": "object", // 类型"properties": { // 字段"name": { //name字段"type": "string", // 类型string"maxLength": 50,//最大长度"pattern": "^[a-zA-Z0-9]*$"// 正则},"sex": {"type": "string","maxLength": 20,"pattern": "^[a-zA-Z0-9]*$"}},"required": ["name","sex"] // 必填项
}

由于我填了中文,就提示错误,

提供一个带数组的json文件字段信息–描述

{"type": "object", // 对象"properties": { // 字段"usertoken": { // token"type": "string", // 字段类型"maxLength": 50,// 最大长度"pattern": "^[a-zA-Z0-9]*$" // 正则},"service": {"type": "string","maxLength": 20,"pattern": "^[a-zA-Z0-9]*$"},"paramJson": {"type": "object","required": ["orderNo"],// 当前对象必填"properties": {"orderNo": {"type": "string","maxLength": 32,"pattern": "^[a-zA-Z0-9]*$"},"declareItems": {"type": "array", // 数组"items": {"type": "object","required": ["ename"],"properties": {"ename": {"type": "string","maxLength": 100,"pattern": "^[a-zA-Z0-9\\s]*$"}}}}}}},"required": ["usertoken","service"]
}

JAVA Json-Schema接口校验利器相关推荐

  1. json Schema 数据校验工具

    JSON Schema官网 文章目录 1:JSON Schema简介 1.1:基础知识 1.2:定义关键字解释 1:$schema 2:type支持数据类型 2.1:string字符串 1:正则表达式 ...

  2. JSON Schema数据校验入门

    快速开始 我们用一个例子来介绍说明 JSON Schema,虽然不可能面面俱到,但是对JSON Schema的基本概念.语法.使用有个较为全面的了解是完全没问题的. 这里假设我们有一个产品类目接口是用 ...

  3. 如何快速写出Json Schema,校验Json Schema

    本文首发于微信公众号: [软测小生] 得到一个Json文件,如何快速的去测试呢? 难道是一个个节点的去验证吗?那显然效率太低了. 一般推荐使用Json Schema(一种Json的数据结构定义)去校验 ...

  4. json schema多种形式_如何快速写出Json Schema,校验Json Schema

    得到一个Json文件,如何快速的去测试呢? 难道是一个个节点的去验证吗?那显然效率太低了. 一般推荐使用Json Schema(一种Json的数据结构定义)去校验. 对于JsonSchema,有很多种 ...

  5. 3 分钟了解 JSON Schema

    大家好,我不是鱼皮. 幸运又不幸,我是一名程序员,他也是一名程序员. 周末,我在开发网站,他在开发游戏,两个人一起写代码,一起写 Bug 头秃,竟也有了一丝别样的浪漫,好不自在! 今天,他遇到了一个后 ...

  6. JSON schema(模式)

    文章目录 JSON schema 一,什么是 JSON Schema 二,定义 Schema 1) 字符串(String) 2) 数值类型 3) 对象 属性(Properties) 额外属性(Asdd ...

  7. JSON Schema入门

    使用Json的好处(什么是Schema): 描述现有的数据格式 提供清晰的人工和机器可读文档 完整的数据结构,有利于自动化测试 完整的数据结构,有利于验证客户端提交数据的质量 什么是JSON Sche ...

  8. 如何利用JSON Schema校验JSON数据格式

    最近笔者在工作中需要监控一批http接口,并对返回的JSON数据进行校验.正好之前在某前端大神的分享中得知这个神器的存在,调研一番之后应用在该项目中,并取得了不错的效果,特地在此分享给各位读者. 什么 ...

  9. JSON Schema校验数据

    参考 JSON Schema 规范(中文版)官方网站JSON Schema 对于数据对接系统来说,接口的数据入参校验尤为重要,使用javax.validation相关注解进行校验对于java对象的关联 ...

最新文章

  1. java 内存溢出-与gc
  2. 公网开放的plc设备——一种新型的后门
  3. 【数理知识】《数值分析》李庆扬老师-第2章-插值法
  4. c 语言程序设计教程 沈显君 答案,CD3计算机实践《C/C++语言程序设计》报告模板2.doc...
  5. orgman set触发的pricing set创建逻辑
  6. 将log4cplus.so集成到linux下报undefined reference to 错误
  7. pyspider爬虫框架
  8. Google AJAX 搜索 API
  9. 提交数据库访问性能一些简单措施
  10. mysql查询不超过19_mysql45讲 19.为什么我只查一行的语句,也执行这么慢?
  11. python ggplot_python数据可视化系列---谁是ggplot2的更好python实现
  12. left join on
  13. Matlab 多行屏蔽或注释方法
  14. 华为云服务器参数配置文件,华为云服务器参数配置文件
  15. Oracle Report開發(1)--Oracle Report Builder
  16. 根据原厂uboot进行移植
  17. cad指示箭头快捷键命令_CAD箭头引注快捷键是什么?
  18. 美国大学计算机牛校简介
  19. 【夏目鬼鬼分享】SpringBoot集成热部署(IDEA)
  20. 绿色版 MySQL 安装配置的正确操作步骤

热门文章

  1. 根据气象预警等级颜色获取图片名称,返回对应图片url的方法
  2. 弹道分析软件_火控系统弹道解算软件的测试方法
  3. flv封装H264+AAC[附完整代码]
  4. 锐取录播系统服务器设置ip,锐取录播系统安装手册
  5. 计算机EI会议论文,和EI期刊论文有什么区别? - 易智编译EaseEditing
  6. makedown公式和绘图
  7. 不带管理口的mellanox交换机打开端口一分二特性
  8. 项目管理(如何进行项目采购管理)
  9. 模拟电路设计(40)---你真的懂“接地”吗?
  10. STP/RSTP/MSTP的概念及特点