本系列旨在介绍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. FreeSWITCH添加h264编码及pcap视频提取

    操作系统 :CentOS 7.6_x64.Windows 10_x64 FreeSWITCH版本 :1.10.9 Python版本:3.9.2 一.启用h264相关模块 这里以 mod_openh26 ...

  2. 8月Node服务的3场事故

    有句话叫每一起严重事故的背后,必然有 29 次轻微事故和 300 起未遂先兆以及 1000 起事故隐患. 而我最近更是碰到了 3 起比较严重的线上事故,都是大意惹的祸. 一.数据库锁死 第一起事故发生 ...

  3. Ubuntu 14.04解决登录界面无限循环的方法

    在Ubuntu下配置Android的环境时,想像在Windows中那样在终端中直接启动adb,以为Linux和Windows一样,将adb的路径添加到环境变量中,于是将adb的路径也export到/e ...

  4. MySQL8.0默认加密连接方式

    Mysql8.0开始默认采用新的caching_sha2_password的身份验证方式,常规老接口会因此无法连接数据库. 为继续使用老的身份验证方式,需显式指定身份验证方式为 mysql_nativ ...

  5. Merge-Lrc 合并歌词的小工具

    Merge-Lrc 背景 音乐区有群友希望各种乱七八糟的歌词(lrc 格式居多,里面甚至还有翻译)可以整理成单一的文件,或者一个仅翻译的歌词可以和原文的歌词合并.于是就开发了这款工具.地址:https ...

  6. 研发日常踩坑-Mysql分页数据重复

    踩坑描述: 写分页查询接口,order by和limit混用的时候,出现了排序的混乱情况 在进行第N页查询时,出现与第一前面页码的数据一样的记录. 问题 在MySQL中分页查询,我们经常会用limit ...

  7. js滚动条滚动到底部和顶部

    <!DOCTYPE html> <html> <head> <title></title> <style type="tex ...

  8. Go命令大全:全面解析与实践

    本文详尽地探讨了Go语言的内建命令集,包括但不限于go build.go run.go get等.文章首先列举了所有常用的Go命令,并用表格形式简洁地解释了它们的功能.随后,我们逐一深入讲解了每个命令 ...

  9. VK Cup 2016 - Round 1 (CF639)

    A. Bear and Displayed Friends Div2 的题,不写. B. Bear and Forgotten Tree 3 这种东西怎么评蓝的? Description 给定 \(n ...

  10. MongoDB-SQL语法

    MongoDB-SQL语法 可视化软件:Navicat 1. MongoDB-查询 db.getCollection('表名').find({}); db.getCollection('表名').fi ...