国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Json Schema簡介和Json Schema的高性能.net實現(xiàn)庫 LateApexEarlySpeed.Json.Schema

這篇具有很好參考價值的文章主要介紹了Json Schema簡介和Json Schema的高性能.net實現(xiàn)庫 LateApexEarlySpeed.Json.Schema。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

什么是Json Schema ?

Json schema是一種聲明式語言,它可以用來標識Json的結(jié)構(gòu),數(shù)據(jù)類型和數(shù)據(jù)的具體限制,它提供了描述期望Json結(jié)構(gòu)的標準化方法。
利用Json Schema, 你可以定義Json結(jié)構(gòu)的各種規(guī)則,以便確定Json數(shù)據(jù)在各個子系統(tǒng)中交互傳輸時保持兼容和一致的格式。

一般來說,系統(tǒng)可以自己實現(xiàn)邏輯來判斷當前json是否滿足接口要求,比如是否某個字段存在,是否屬性值是有效的。但當驗證需求變得復雜后,比如有大量嵌套json結(jié)構(gòu),屬性之間的復雜關(guān)聯(lián)限制等等,則容易編寫出考慮不全的驗證代碼。另外,當系統(tǒng)需要動態(tài)的json數(shù)據(jù)要求,比如先由用戶自己決定他需要的json結(jié)構(gòu),然后系統(tǒng)根據(jù)用戶表達的定制化json結(jié)構(gòu)需求,幫助用戶驗證后續(xù)的json數(shù)據(jù)。這種系統(tǒng)代碼編譯時無法確定的json結(jié)構(gòu),就需要另一種解決方案。

Json Schema就是針對這種問題的比較自然的解決方案。它可以讓你或你的用戶描述希望的json結(jié)構(gòu)和值的內(nèi)容限制,有效屬性,是否是required, 還有有效值的定義,等等。。利用Json Schema, 人們可以更好的理解Json結(jié)構(gòu),而且程序也可以根據(jù)你的Json Schema驗證Json數(shù)據(jù)。
Json Schema語法的學習見官方介紹。

比如下面的一個簡單例子,用.net下的Json Schema實現(xiàn)庫library LateApexEarlySpeed.Json.Schema進行Json數(shù)據(jù)的驗證:

Json Schema (文件:schema.json):

{
  "type": "object",
  "properties": {
    "propBoolean": {
      "type": "boolean"
    },
    "propArray": {
      "type": "array",
      "uniqueItems": true
    }
  }
}

Json 數(shù)據(jù) (文件:instance.json):

{
  "propBoolean": true,
  "propArray": [ 1, 2, 3, 4, 4 ]
}

C# 代碼:

            string jsonSchema = File.ReadAllText("schema.json");
            string instance = File.ReadAllText("instance.json");

            var jsonValidator = new JsonValidator(jsonSchema);
            ValidationResult validationResult = jsonValidator.Validate(instance);

            if (validationResult.IsValid)
            {
                Console.WriteLine("good");
            }
            else
            {
                Console.WriteLine($"Failed keyword: {validationResult.Keyword}");
                Console.WriteLine($"ResultCode: {validationResult.ResultCode}");
                Console.WriteLine($"Error message: {validationResult.ErrorMessage}");
                Console.WriteLine($"Failed instance location: {validationResult.InstanceLocation}");
                Console.WriteLine($"Failed relative keyword location: {validationResult.RelativeKeywordLocation}");
            }

輸出:

Failed keyword: uniqueItems
ResultCode: DuplicatedArrayItems
Error message: There are duplicated array items
Failed instance location: /propArray
Failed relative keyword location: /properties/propArray/uniqueItems

LateApexEarlySpeed.Json.Schema中文介紹

項目原始文檔:https://github.com/lateapexearlyspeed/Lateapexearlyspeed.JsonSchema.Doc

中文文檔:
LateApexEarlySpeed.Json.Schema是2023年12月發(fā)布的一個新的.net下的Json Schema實現(xiàn)庫library,基于截止到2023年12月為止最新版的Json schema - draft 2020.12。
Json Schema驗證功能經(jīng)過了official json schema test-suite for draft 2020.12的測試。(部分排除的用例見下面的已知限制章節(jié))

主要特點:

  • 基于微軟.net下默認的System.Text.Json而非經(jīng)典的Newtonsoft.Json
  • 高性能:和已有的知名且杰出的.net下的一些JsonSchema library相比,具有很好的性能 (在common case下,利用BenchmarkDotnet進行的性能測試)。用戶請根據(jù)自己的使用場景進行性能驗證

一些性能測試結(jié)果 (下面的測試比較都是在同樣的使用方式下進行,見 性能建議 ):
12th Gen Intel Core i7-12800H, 1 CPU, 20 logical and 14 physical cores

[Host] : .NET 6.0.25 (6.0.2523.51912), X64 RyuJIT AVX2

DefaultJob : .NET 6.0.25 (6.0.2523.51912), X64 RyuJIT AVX2

有效數(shù)據(jù)用例:

Method Mean Error StdDev Gen0 Gen1 Allocated
ValidateByPopularSTJBasedValidator 29.80 us 0.584 us 0.573 us 4.4556 0.2441 55.1 KB
ValidateByThisValidator 15.99 us 0.305 us 0.300 us 1.9531 - 24.2 KB

無效數(shù)據(jù)用例:

Method Mean Error StdDev Median Gen0 Gen1 Allocated
ValidateByPopularSTJBasedValidator 65.04 us 2.530 us 7.341 us 66.87 us 4.5776 0.1221 56.42 KB
ValidateByThisValidator 15.47 us 1.160 us 3.421 us 17.14 us 1.4954 - 18.45 KB

Note: "STJ"是"System.Text.Json"的縮寫,這個是.net sdk里默認帶的json基礎(chǔ)包, LateApexEarlySpeed.Json.Schema這個庫也是基于這個STJ編寫的。

基準Schema:

{
  "$id": "http://main",
  "type": "object",

  "additionalProperties": false,
  "patternProperties": {
    "propB*lean": {
      "type": "boolean"
    }
  },
  "dependentRequired": {
    "propNull": [ "propBoolean", "propArray" ]
  },
  "dependentSchemas": {
    "propNull": {
      "type": "object"
    }
  },
  "propertyNames": true,
  "required": [ "propNull", "propBoolean" ],
  "maxProperties": 100,
  "minProperties": 0,
  "properties": {
    "propNull": {
      "type": "null"
    },
    "propBoolean": {
      "type": "boolean",
      "allOf": [
        true,
        { "type": "boolean" }
      ]
    },
    "propArray": {
      "type": "array",
      "anyOf": [ false, true ],
      "contains": { "type": "integer" },
      "maxContains": 100,
      "minContains": 2,
      "maxItems": 100,
      "minItems": 1,
      "prefixItems": [
        { "type": "integer" }
      ],
      "items": { "type": "integer" },
      "uniqueItems": true
    },
    "propNumber": {
      "type": "number",
      "if": {
        "const": 1.5
      },
      "then": true,
      "else": true,
      "enum": [ 1.5, 0, 1 ]
    },
    "propString": {
      "type": "string",
      "maxLength": 100,
      "minLength": 0,
      "not": false,
      "pattern": "abcde"
    },
    "propInteger": {
      "$ref": "#/$defs/typeIsInteger",
      "exclusiveMaximum": 100,
      "exclusiveMinimum": 0,
      "maximum": 100,
      "minimum": 0,
      "multipleOf": 0.5,
      "oneOf": [ true, false ]
    }
  },
  "$defs": {
    "typeIsInteger": { "$ref": "http://inside#/$defs/typeIsInteger" },
    "toTestAnchor": {
      "$anchor": "test-anchor"
    },
    "toTestAnotherResourceRef": {
      "$id": "http://inside",
      "$defs": {
        "typeIsInteger": { "type": "integer" }
      }
    }
  }
}

有效基準數(shù)據(jù):

{
  "propNull": null,
  "propBoolean": true,
  "propArray": [ 1, 2, 3, 4, 5 ],
  "propNumber": 1.5,
  "propString": "abcde",
  "propInteger": 1
}

無效基準數(shù)據(jù):

{
  "propNull": null,
  "propBoolean": true,
  "propArray": [ 1, 2, 3, 4, 4 ], // Two '4', duplicated
  "propNumber": 1.5,
  "propString": "abcde",
  "propInteger": 1
}

該實現(xiàn)庫(implementation library)之后可能會transfer成開源項目。

基礎(chǔ)用法

安裝Nuget package

Install-Package LateApexEarlySpeed.Json.Schema
string jsonSchema = File.ReadAllText("schema.json");
string instance = File.ReadAllText("instance.json");

var jsonValidator = new JsonValidator(jsonSchema);
ValidationResult validationResult = jsonValidator.Validate(instance);

if (validationResult.IsValid)
{
    Console.WriteLine("good");
}
else
{
    Console.WriteLine($"Failed keyword: {validationResult.Keyword}");
    Console.WriteLine($"ResultCode: {validationResult.ResultCode}");
    Console.WriteLine($"Error message: {validationResult.ErrorMessage}");
    Console.WriteLine($"Failed instance location: {validationResult.InstanceLocation}");
    Console.WriteLine($"Failed relative keyword location: {validationResult.RelativeKeywordLocation}");
    Console.WriteLine($"Failed schema resource base uri: {validationResult.SchemaResourceBaseUri}");
}

輸出信息

當json數(shù)據(jù)驗證失敗后,可以查看錯誤數(shù)據(jù)的具體信息:

  • IsValid: As summary indicator for passed validation or failed validation.

  • ResultCode: The specific error type when validation failed.

  • ErrorMessage: the specific wording for human readable message

  • Keyword: current keyword when validation failed

  • InstanceLocation: The location of the JSON value within the instance being validated. The value is a JSON Pointer.

  • RelativeKeywordLocation: The relative location of the validating keyword that follows the validation path. The value is a JSON Pointer, and it includes any by-reference applicators such as "$ref" or "$dynamicRef". Eg:

    /properties/width/$ref/minimum
    
  • SubSchemaRefFullUri: The absolute, dereferenced location of the validating keyword when validation failed. The value is a full URI using the canonical URI of the relevant schema resource with a JSON Pointer fragment, and it doesn't include by-reference applicators such as "$ref" or "$dynamicRef" as non-terminal path components. Eg:

    https://example.com/schemas/common#/$defs/count/minimum
    
  • SchemaResourceBaseUri: The absolute base URI of referenced json schema resource when validation failed. Eg:

    https://example.com/schemas/common
    

性能建議

盡可能的重用已實例化的JsonValidator實例(JsonValidator可以簡單理解為代表一個json schema驗證文檔)來驗證json數(shù)據(jù),以便獲得更高性能

外部json schema依賴的支持

除了自動支持當前schema文檔內(nèi)的引用關(guān)系,還支持外部json schema依賴:

  • 本地schema依賴文本
var jsonValidator = new JsonValidator(jsonSchema);
string externalJsonSchema = File.ReadAllText("schema2.json");
jsonValidator.AddExternalDocument(externalJsonSchema);
ValidationResult validationResult = jsonValidator.Validate(instance);
  • 遠程schema url (實現(xiàn)庫將訪問網(wǎng)絡(luò)來獲得遠程的schema)
var jsonValidator = new JsonValidator(jsonSchema);
await jsonValidator.AddHttpDocumentAsync(new Uri("http://this-is-json-schema-document"));
ValidationResult validationResult = jsonValidator.Validate(instance);

自定義keyword的支持

除了json schema specification中的標準keywords之外,還支持用戶創(chuàng)建自定義keyword來實現(xiàn)額外的驗證需求:

{
  "type": "object",
  "properties": {
    "prop1": {
      "customKeyword": "Expected value"
    }
  }
}
ValidationKeywordRegistry.AddKeyword<CustomKeyword>();
[Keyword("customKeyword")] // It is your custom keyword name
[JsonConverter(typeof(CustomKeywordJsonConverter))] // Use 'CustomKeywordJsonConverter' to deserialize to 'CustomKeyword' instance out from json schema text
internal class CustomKeyword : KeywordBase
{
    private readonly string _customValue; // Simple example value

    public CustomKeyword(string customValue)
    {
        _customValue = customValue;
    }

    // Do your custom validation work here
    protected override ValidationResult ValidateCore(JsonInstanceElement instance, JsonSchemaOptions options)
    {
        if (instance.ValueKind != JsonValueKind.String)
        {
            return ValidationResult.ValidResult;
        }

        return instance.GetString() == _customValue
            ? ValidationResult.ValidResult
            : ValidationResult.CreateFailedResult(ResultCode.UnexpectedValue, "It is not my expected value.", options.ValidationPathStack, Name, instance.Location);
    }
}
internal class CustomKeywordJsonConverter : JsonConverter<CustomKeyword>
{
    // Library will input json value of your custom keyword: "customKeyword" to this method.
    public override CustomKeyword? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // Briefly: 
        return new CustomKeyword(reader.GetString()!);
    }

    public override void Write(Utf8JsonWriter writer, CustomKeyword value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

Format支持

目前l(fā)ibrary支持如下format:

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

Format 驗證需要顯式enable, 當驗證數(shù)據(jù)時,請傳入配置好的 JsonSchemaOptions:

jsonValidator.Validate(instance, new JsonSchemaOptions{ValidateFormat = true});

如果需要自定義format驗證,可以實現(xiàn)一個FormatValidator子類并注冊:

[Format("custom_format")] // this is your custom format name in json schema
public class TestCustomFormatValidator : FormatValidator
{
    public override bool Validate(string content)
    {
        // custom format validation logic here...
    }
}

// register it globally
FormatRegistry.AddFormatType<TestCustomFormatValidator>();

Other extension usage doc is to be continued .

限制

  • 目前l(fā)ibrary關(guān)注于驗證,暫不支持annotation
  • 因為暫不支持annotation, 所以不支持如下keywords: unevaluatedProperties, unevaluatedItems
  • 目前不支持 content-encoded string

問題報告

歡迎把使用過程中遇到的問題和希望增加的功能發(fā)到github repo issue中文章來源地址http://www.zghlxwxcb.cn/news/detail-762411.html

More doc is to be written

到了這里,關(guān)于Json Schema簡介和Json Schema的高性能.net實現(xiàn)庫 LateApexEarlySpeed.Json.Schema的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 一個高性能類型安全的.NET枚舉實用開源庫

    一個高性能類型安全的.NET枚舉實用開源庫

    從零構(gòu)建.Net前后端分離項目 枚舉應(yīng)該是我們編程中,必不可少的了,今天推薦一個.NET枚舉實用開源庫,它提供許多方便的擴展方法,方便開發(fā)者使用開發(fā)。 01 項目簡介 Enums.NET是一個.NET枚舉實用程序庫,專注于為枚舉提供豐富的操作方法。它支持.NET Framework和.Net Core。它主

    2024年02月05日
    瀏覽(27)
  • 【中間件-Openjob】高性能任務(wù)調(diào)度框架Openjob簡介及快速搭建

    【中間件-Openjob】高性能任務(wù)調(diào)度框架Openjob簡介及快速搭建

    一款分布式高性能任務(wù)調(diào)度框架,支持多種定時任務(wù)、延時任務(wù)、工作流設(shè)計、輕量級分布式計算、無限水平擴容,并具有較高的可伸縮性和容錯性,以及完善權(quán)限管理、強大的告警監(jiān)控、原生支持多語言。 基礎(chǔ)信息 中文官網(wǎng) :https://openjob.io/zh-Hans/ 開源地址 :https://githu

    2024年02月12日
    瀏覽(27)
  • 【分布式云儲存】高性能云存儲MinIO簡介與Docker部署集群

    【分布式云儲存】高性能云存儲MinIO簡介與Docker部署集群

    分布式存儲服務(wù)一直以來是中大型項目不可或缺的一部分,一般常用的商用文件服務(wù)有七牛云、阿里云等等,自建的開源文件服務(wù)有FastDFS、HDFS等等。但是對于這些方案有的需要付費有些卻太過于笨重,今天我們就分享一款輕量級完全可替代生產(chǎn)的高性能分布式儲存服務(wù)Mini

    2024年02月07日
    瀏覽(27)
  • .NET 高性能I/O之道:深度探索 System.IO.Pipelines

    ??作者:科技、互聯(lián)網(wǎng)行業(yè)優(yōu)質(zhì)創(chuàng)作者 ??專注領(lǐng)域:.Net技術(shù)、軟件架構(gòu)、人工智能、數(shù)字化轉(zhuǎn)型、DeveloperSharp、微服務(wù)、工業(yè)互聯(lián)網(wǎng)、智能制造 ??歡迎關(guān)注我(Net數(shù)字智慧化基地),里面有很多 高價值 技術(shù)文章, 是你刻苦努力也積累不到的經(jīng)驗 ,能助你快速成長。升職

    2024年03月11日
    瀏覽(28)
  • 002. 使用最小堆實現(xiàn)高性能定時器實現(xiàn)

    定時器原理 – 任務(wù)的容器(要求:數(shù)據(jù)結(jié)構(gòu)有序或相對有序;能快速查找最近觸發(fā)的定時任務(wù)) + 觸發(fā)條件(可以通過帶有time_out的系統(tǒng)函數(shù),如epoll_wait的最后一個參數(shù)); 最小堆的特點 – 是一顆完全二叉樹; – 某個節(jié)點的值總是小于等于它子節(jié)點的值(即定位到最小值的時間

    2024年02月07日
    瀏覽(33)
  • Kafka是如何實現(xiàn)高性能IO

    ? 批量處理是一種非常有效的提升系統(tǒng)吞吐量的方法。在 Kafka 內(nèi)部,消息都是以“批”為單位處理的。一批消息從發(fā)送端到接收端,是如何在 Kafka 中流轉(zhuǎn)的呢? Kafka 的 Producer 只提供了單條發(fā)送的 send() 方法,并沒有提供任何批量發(fā)送的接口。 kafka 根本就沒有提供單條發(fā)送

    2024年02月11日
    瀏覽(27)
  • 通過Span實現(xiàn)高性能數(shù)組,實例解析

    通過Span實現(xiàn)高性能數(shù)組,實例解析

    SpanT 是 C# 7.2 引入的一個強大的數(shù)據(jù)結(jié)構(gòu),用于表示內(nèi)存中的一塊連續(xù)數(shù)據(jù)。它可以用于實現(xiàn)高性能的數(shù)組操作,而無需額外的內(nèi)存分配。在本文中,我將詳細介紹如何使用 SpanT 來實現(xiàn)高性能數(shù)組操作,并提供一些示例代碼來說明其用法。 SpanT 是 System.Memory 命名空間中的結(jié)構(gòu)

    2024年02月05日
    瀏覽(30)
  • uni-app如何實現(xiàn)高性能

    uni-app如何實現(xiàn)高性能

    這篇文章主要講解uni-app如何實現(xiàn)高性能的問題? 什么是uni-app? 簡單說一下什么是uni-app,uni-app是繼承自vue.js,對vue做了輕度定制,并且實現(xiàn)了完整的組件化開發(fā),并且支持多端發(fā)布的一種架構(gòu),開發(fā)的項目可適配多平臺。 過內(nèi)前端開發(fā)的大致分歧? 國內(nèi)前端開發(fā)生態(tài)現(xiàn)在的

    2024年04月11日
    瀏覽(29)
  • Docker與Kafka:實現(xiàn)高性能流處理

    Docker 和 Kafka 都是現(xiàn)代技術(shù)中的重要組成部分,它們各自在不同領(lǐng)域發(fā)揮著重要作用。Docker 是一個開源的應(yīng)用容器引擎,用于自動化部署、創(chuàng)建、運行和管理應(yīng)用程序。Kafka 是一個分布式流處理平臺,用于構(gòu)建實時數(shù)據(jù)流管道和流處理應(yīng)用程序。 在大數(shù)據(jù)和實時數(shù)據(jù)處理領(lǐng)域

    2024年02月20日
    瀏覽(32)
  • 【消息隊列】Kafka如何實現(xiàn)高性能IO

    【消息隊列】Kafka如何實現(xiàn)高性能IO

    我們直到Kafka是一個自稱高性能的消息隊列引擎,一般來說對于中間件的設(shè)計需要從計算、存儲、網(wǎng)絡(luò)三方面進行下手,而消息從產(chǎn)生到消費,也會經(jīng)歷多個流程,比如在生產(chǎn)者端采用異步同步方式發(fā)送,采用高效的壓縮算法,高效的序列化方式,以及網(wǎng)絡(luò)IO等。那么Kafka主要

    2023年04月13日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包