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

本系列旨在介绍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试一下:

csharp 复制代码
var jsonValidator = new JsonValidator("{}");
ValidationResult validationResult = jsonValidator.Validate("123");

Assert.True(validationResult.IsValid);

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

csharp 复制代码
ValidationResult result = new JsonValidator("true").Validate("123");
Assert.True(result.IsValid);
csharp 复制代码
ValidationResult result = new JsonValidator("false").Validate("123");
Assert.False(result.IsValid);

type 关键字

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

csharp 复制代码
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."
csharp 复制代码
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长度:

csharp 复制代码
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.

csharp 复制代码
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来举例子吧:

csharp 复制代码
string schema = """
{ 
  "type": "string",
  "format": "email"
}
""";
var jsonValidator = new JsonValidator(schema);
Assert.True(jsonValidator.Validate("\"[email protected]\"", 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这里。

相关推荐
白熊1883 小时前
【计算机视觉】CV实战项目 -深度解析PaddleSegSharp:基于PaddleSeg的.NET图像分割解决方案
人工智能·计算机视觉·.net
互联网打工人no13 小时前
.NET8 依赖注入组件
开发语言·c#·.net·ioc
HelloRevit15 小时前
.NET 10 中的新增功能
.net
o0向阳而生0o15 小时前
28、.NET 中元数据是什么?
microsoft·c#·.net
冰茶_18 小时前
.NET MAUI 发展历程:从 Xamarin 到现代跨平台应用开发框架
学习·microsoft·微软·c#·.net·xamarin
醉酒的李白、19 小时前
.NET仓储层在 using 块中创建 SqlSugarClient 的风险
.net·仓储模式设计
Iotfsd1 天前
.NET写的开源工业物联网网关(IoTGateway)
物联网·c#·.net·dotnet·边缘网关·雾计算·工业物联网智能网关
界面开发小八哥2 天前
界面开发框架DevExpress XAF实践:如何在Blazor项目中集成.NET Aspire?(二)
.net·界面控件·devexpress·ui开发·xaf
码观天工3 天前
C#高性能开发之类型系统:从C# 7.0 到C# 14的类型系统演进全景
性能优化·c#·.net·memory·高性能·record·c#14·类型系统