本系列旨在介绍Json Schema的常见用法,以及.net实现库Lateapexearlyspeed.Json.Schema的使用


这篇文章将介绍Json Schema中的type关键字,和string类型的常见验证功能。用例基于.net的LateApexEarlySpeed.Json.Schema nuget package。这是新创建的一个 Json Schema在.net下的高性能实现库。


最简单的Json Schema

就像其他各种Schema一样,Json Schema的一个基本且核心的目的是对Json数据进行描述,以便进行验证。Json Schema其实是一个由各种keywords组合而成的“容器”,每个keyword有不同的作用范围和验证功能。一个最简单的Json Schema是空Json object,它代表所有的Json 数据都是有效的 (因为它没有带着任何keyword):

{}

让我们用 .net下的Lateapexearlyspeed.Json.Schema library试一下:

var jsonValidator = new JsonValidator("{}");
ValidationResult validationResult = jsonValidator.Validate("123"); Assert.True(validationResult.IsValid);

除了空Json object, 还可以用true和false分别表示“任何数据都符合”和“任何数据都不符合”:

ValidationResult result = new JsonValidator("true").Validate("123");
Assert.True(result.IsValid);
ValidationResult result = new JsonValidator("false").Validate("123");
Assert.False(result.IsValid);

type 关键字

一般来说,大家用的最多的关键字(keyword)应该是type, 它用来描述数据应该是哪种类型的。比如下面的例子,只允许json数据是string而不能是其他类型:

string schema = """
{ "type": "string" }
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"abc\"").IsValid);
Assert.False(jsonValidator.Validate("123").IsValid);

type关键字支持如下内容:string,number,integer,object,array,boolean,null。

String

String type用于表示数据是json string type。

"This is string json token."
string schema = """
{ "type": "string" }
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"abc\"").IsValid);
Assert.False(jsonValidator.Validate("123").IsValid);

长度

对于String json token来说,可以用minLength和maxLength关键字来表示string长度:

string schema = """
{
"type": "string",
"minLength": 3,
"maxLength": 5
}
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"abc\"").IsValid); ValidationResult result = jsonValidator.Validate("\"ab\"");
Assert.False(result.IsValid);
Assert.Equal("minLength", result.Keyword);
Assert.Equal(ResultCode.StringLengthOutOfRange, result.ResultCode);
Assert.Equal("String instance's length is 2 which is less than '3'", result.ErrorMessage);

正则表达式

正则表达式的关键字是pattern,它用来验证string数据是否匹配要求的pattern.

string schema = """
{
"type": "string",
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"(888)555-1212\"").IsValid); ValidationResult result = jsonValidator.Validate("\"(800)FLOWERS\"");
Assert.False(result.IsValid);
Assert.Equal("pattern", result.Keyword);
Assert.Equal(ResultCode.RegexNotMatch, result.ResultCode);
Assert.Equal("Regex: '^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$' cannot find match in instance: '(800)FLOWERS'", result.ErrorMessage);

字符串格式

有时人们需要表示数据是一些常用的格式,比如是邮箱地址,uri, ip地址,日期时间,GUID 等。虽然可以用正则表达式pattern来手动解决,但json schema还是规定了format关键字来描述一些常用格式,以方便使用。LateApexEarlySpeed.Json.Schema默认支持如下format:

  • uri
  • uri-reference
  • date
  • time
  • date-time
  • email
  • uuid
  • hostname
  • ipv4
  • ipv6
  • json-pointer
  • regex

它们各自的具体含义可参考官方说明

这里仅用email format来举例子吧:

string schema = """
{
"type": "string",
"format": "email"
}
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"hello@world.com\"", new JsonSchemaOptions{ValidateFormat = true}).IsValid); ValidationResult result = jsonValidator.Validate("\"@world.com\"", new JsonSchemaOptions { ValidateFormat = true });
Assert.False(result.IsValid);
Assert.Equal("format", result.Keyword);
Assert.Equal(ResultCode.InvalidFormat, result.ResultCode);
Assert.Equal("Invalid string value for format:'email'", result.ErrorMessage);

更完整的字符串相关关键字请参考官方json schema specification。


之后的文章会继续介绍Json Schema的其他功能和LateApexEarlySpeed.Json.Schema的使用。


LateApexEarlySpeed.Json.Schema是新的Json Schema的.net library, nuget package下载:https://www.nuget.org/packages/Lateapexearlyspeed.Json.Schema

github doc repo: https://github.com/lateapexearlyspeed/Lateapexearlyspeed.JsonSchema.Doc, 使用中遇到的问题,欢迎发到repo issue这里。

Json Schema介绍 和 .net 下的实践 - 基于Lateapexearlyspeed.Json.Schema - 基础1 - type关键字和string类型的更多相关文章

  1. Json.Net系列教程 1.Json.Net介绍及实例

    原文 Json.Net系列教程 1.Json.Net介绍及实例 本系列教程假设读者已经对Json有一定的了解,关于Json在这里不多说.本系列教程希望能对读者开发涉及到Json的.Net项目有一定的帮 ...

  2. Solr系列三:solr索引详解(Schema介绍、字段定义详解、Schema API 介绍)

    一.Schema介绍 1. Schema 是什么? Schema:模式,是集合/内核中字段的定义,让solr知道集合/内核包含哪些字段.字段的数据类型.字段该索引存储. 2. Schema 的定义方式 ...

  3. spring 4.x下让http请求返回json串

    当前很多应用已经开始将响应返回为json串,所以基于springframework框架开发的服务端程序,让响应返回json字符串成为了一种常用手段. 这里介绍一下如何在spring-MVC框架下方便快 ...

  4. atitit.基于http json api 接口设计 最佳实践 总结o7

    atitit.基于http  json  api 接口设计 最佳实践 总结o7 1. 需求:::服务器and android 端接口通讯 2 2. 接口开发的要点 2 2.1. 普通参数 meth,p ...

  5. Json.Net介绍及实例

    本系列教程假设读者已经对Json有一定的了解,关于Json在这里不多说.本系列教程希望能对读者开发涉及到Json的.Net项目有一定的帮助.本系列教程是根据官方文档资料和自己项目应用汇总而成.如果觉得 ...

  6. 最近想学Json,请问大家有没有什么好的Json教程介绍一下?

    最近想学json,请问大家有没有什么好的Json教程介绍一下? 最近学完java的框架了,想了解一下json,可是找不到相关视频,请大家有这方面的Json教程好资料就介绍下啦,最后有网址链接啦. {} ...

  7. Day06 DOM4J&schema介绍&xPath

    day06总结 今日内容 XML解析之JAXP( SAX ) DOM4J Schema   三.XML解析器介绍   操作XML文档概述   1 如何操作XML文档 XML文档也是数据的一种,对数据的 ...

  8. Python中的序列化以及pickle和json模块介绍

    Python中的序列化指的是在程序运行期间,变量都是在内存中保存着的,如果我们想保留一些运行中的变量值,就可以使用序列化操作把变量内容从内存保存到磁盘中,在Python中这个操作叫pickling,等 ...

  9. 【重温基础】16.JSON对象介绍

    本文是 重温基础 系列文章的第十六篇. 今日感受:静. 系列目录: [复习资料]ES6/ES7/ES8/ES9资料整理(个人整理) [重温基础]1-14篇 [重温基础]15.JS对象介绍 本章节复习的 ...

  10. SeaweedFS在.net core下的实践方案

    一直对分布式的文件储存系统很感兴趣,最开始关注淘宝的TFS(Taobao File System),好像搁浅了,官方地址无法访问,github上面,各种编译问题,无意间发现了SeaweedFS 链接s ...

随机推荐

  1. frida动态插桩初探

    前言 近期碰到了分析app的需求,就学习了一下 frida的动态插桩技术.frida是一款轻量级HOOK框架,可用于多平台上,例如android.windows.ios等.frida分为两部分,服务端 ...

  2. 【BUU刷题日记】--第二周

    [BUU刷题日记]--第二周 一.[WUSTCTF2020]朴实无华 1 目录爆破 使用dirsearch扫描发现没有结果,因为如果dirsearch请求过快则会导致超出服务器最大请求,扫描不出本来可 ...

  3. [ABC310D] Peaceful Teams 题解

    Peaceful Teams 题目大意 将 \(n\) 个人分成 \(T\) 组,要求每组不能包含敌对的人,问有多少种分法. 思路分析 注意到 \(n,T\) 均很小,考虑爆搜. 注意到直接枚举会枚举 ...

  4. mysql学习之数据备份和恢复

    一.使用mysqldump进行备份 如:将test数据库备份到/tmp/mysql_back/目录下 [root@localhost tmp]# mysqldump -uroot -p111 -l - ...

  5. Python 既是解释型语言,也是编译型语言

    哈喽大家好,我是咸鱼 不知道有没有小伙伴跟我一样,刚开始学习 Python 的时候都听说过 Python 是一种解释型语言,因为它在运行的时候会逐行解释并执行,而 C++ 这种是编译型语言 不过我今天 ...

  6. TechEmpower 22轮Web框架 性能评测:.NET 8 战绩斐然

    自从2022年7月第21轮公布的测试以后,一年后 的2023年10月17日 发布了 TechEmpower 22轮测试报告 刚刚发布:Round 22 results - TechEmpower Fr ...

  7. Java笔记——数组静态初始化开始

    一维数组: 静态初始化: 定义格式:(1)数据类型[] 数组名 = new 数组类型[] (2)数组类型[] 数组名 ={元素1,元素2,.....} 练习:数组元素逆序: public static ...

  8. [OpenWrt]软路由H28K开启USB无线教程

    0x01 背景 H28K软路由带了一个USB2.0的接口,官方说是支持USB无线的:于是就网购了USB转WIFI的设备(芯片:RTL8811CU),拿到手后开心的插上去,发现没有任何反应:在Q裙中询问 ...

  9. mysql--基础管理

    1.docker环境登录mysql PS C:\WINDOWS\system32> docker ps -aCONTAINER ID IMAGE COMMAND CREATED STATUS P ...

  10. 使用reposync工具将yum安装包保存到本地的方法

    使用reposync工具将yum安装包保存到本地的方法 版权声明:原创作品,谢绝转载!否则将追究法律责任. ----- 作者:kirin Anolis7/centos7 1.reposync 1.1. ...