首页 > 其他分享 >Json Schema介绍 和 .net 下的实践 - 基于Lateapexearlyspeed.Json.Schema - 基础1 - type关键字和string类型

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

时间:2024-01-14 11:34:46浏览次数:26  
标签:Lateapexearlyspeed string jsonValidator Assert Json result Schema

本系列旨在介绍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("\"[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这里。

标签:Lateapexearlyspeed,string,jsonValidator,Assert,Json,result,Schema
From: https://www.cnblogs.com/dotnet-diagnostic/p/17963484

相关文章

  • C#调用webapi发送带json参数的post请求
    嗯。。很久不更新,因为跳槽新公司了,要学的东西太多太忙了。也没时间记录,今天又写了一个C#调用webapi发送带json参数的post请求拿数据的方法,所以来到这里记录一下///<paramname="url">请求地址</param>///<paramname="jsonParas">请求体</param>///<paramnam......
  • C#将从数据库查处的table格式的数据转为json
    这里的代码是封装好的类,将Datatable作为参数传进来即可解析出json格式的数据,看代码publicstaticstringToJson(DataTabledt){intcount=dt.Rows.Count;//将DataTable格式的数据转换成json格式StringBuilderjsonBuilder=ne......
  • SpringBoot集成Jackson实现JSON序列化
    一、前言Jackson是一个在Java中常用的JSON序列化和反序列化库,它具有操作简单、性能优秀、支持多种数据格式等特点,被广泛应用于各种服务端开发中。SpringMVC框架的默认json解析器也是Jackson。当前常见的json解析器还有Gson、fastjson等,jackson的优势是解析大的json文件处理速度快,运......
  • springboot mybatis postgres 对于json类型的字段转换
    在SpringBoot与MyBatis结合使用时,处理PostgreSQL中的JSON类型字段的转换可以分为以下步骤:自定义TypeHandler:为了在Java实体类与数据库的JSON类型字段之间进行转换,需要创建一个自定义的 TypeHandler。例如,针对JSONObject类型的转换器可以这样实现:importorg.apache.ibatis.type.B......
  • Schema “public“ has version 1.0.0, but no migration could be resolved in the c
    该错误信息是由Flyway报告的,指出在应用程序的数据库迁移过程中遇到了问题。Flyway是一种流行的数据库迁移工具,用于版本控制数据库模式的变化。具体来说,错误信息Schema"public"hasversion1.0.0,butnomigrationcouldberesolvedintheconfiguredlocations!表明以下......
  • Chrome 浏览器插件 V3 版本 Manifest.json 文件中 Action 的类型(Types)、方法(Methods)和
    一、类型(Types)一、OpenPopupOptions1.属性windowId:number可选打开操作弹出式窗口的窗口ID。如果未指定,则默认为当前活动窗口。二、TabDetails1.属性tabId:number可选要查询其状态的标签页ID。如果未指定标签页,则返回非标签页专属状态。三、UserSettin......
  • pyspark json数据解析
    PySpark中的JSON数据解析在大数据处理中,JSON(JavaScriptObjectNotation)是一种常用的数据格式。它以易读的文本形式表示数据,常用于跨平台数据交换。在PySpark中,我们可以使用JSON数据作为输入,并使用内置的函数解析和处理这些数据。本文将介绍如何在PySpark中解析JSON数据,并提供相关......
  • 无涯教程-JSON - Python编程
    本章介绍如何使用Python编程语言编码和解码JSON对象。让我们从准备环境开始,以使用Python进行JSON编程。在开始使用Python编码和解码JSON之前,您需要安装任何可用的JSON模块,在本教程中,我们已经下载并安装了Demjson,如下所示-$tarxvfzdemjson-1.6.tar.gz$cddemjson-1.6$pyt......
  • 无涯教程-JSON - Perl编程
    本章介绍如何使用Perl编程语言编码和解码JSON对象,让我们从准备环境开始,开始使用PerlforJSON进行编程。在使用Perl编码和解码JSON之前,需要安装JSON模块,该模块可以从CPAN获得。下载JSON-2.53.tar.gz或任何其他最新版本后,请按照以下步骤操作-$tarxvfzJSON-2.53.tar.gz$cdJSO......
  • 软件测试/测试开发全日制|Pyest结合json实现数据驱动测试
    前言数据驱动测试是提高代码覆盖率和可靠性的重要方法。结合pytest和JSON(JavaScript对象表示)文件可以轻松实现数据驱动测试。和CSV文件类似,Python读取json文件也不需要借助其他的第三方库,因此我们不需要进行额外的环境安装。下面是如何使用pytest和JSON文件进行数据驱动测试的步骤......