zoukankan      html  css  js  c++  java
  • Json.Net使用JSON Schema验证JSON格式

    Json.NET supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. It sits under the Newtonsoft.Json.Schema namespace.

    Json.NET通过JsonSchemaJsonValidatingReader类,支持JSON Schema标准。这两个类位于Newtonsoft.Json.Schema命名空间。

    JSON Schema is used to validate the structure and data types of a piece of JSON, similar to XML Schema for XML. Read more about JSON Schema at json-schema.org

    JSON Schema用来验证Json的结构以及数据类型,类似于XML的XML Schema。关于更多JSON Schema的信息可以参见json-schema.org

    Validating with JSON Schema  使用JSON Schema验证

    The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema.

    测试Json是否合符规定的最简便方法就是加载这个Json字符串到JObject或者Jarray,然后与JSON Schema一起调用IsValid(JToken, JsonSchema)

    string schemaJson = @"{ 'description': 'A person', 'type': 'object','properties': { 'name': {'type':'string'}, 'hobbies': {'type': 'array',  'items': {'type':'string'}  } }}";
    
    JsonSchema schema = JsonSchema.Parse(schemaJson);
    
    JObject person = JObject.Parse(@"{  'name': 'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']}");
    
    bool valid = person.IsValid(schema);
    // true

    To get validation error messages use the IsValid(JToken, JsonSchema, IList<String>) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

    要得到验证错误的消息可以用IsValid(JToken, JsonSchema, IList<String>)Validate(JToken, JsonSchema, ValidationEventHandler)重载。

    JsonSchema schema = JsonSchema.Parse(schemaJson);
    
    JObject person = JObject.Parse(@"{ 'name': null, 'hobbies': ['Invalid content', 0.123456789]}");
    
    IList<string> messages;
    
    bool valid = person.IsValid(schema, out messages);
    // false
    // Invalid type. Expected String but got Null. Line 2, position 21.
    // Invalid type. Expected String but got Float. Line 3, position 51.

    Internally IsValid uses JsonValidatingReader to perform the JSON Schema validation. To skip the overhead of loading JSON into a JObject/JArray, validating the JSON and then deserializing the JSON into a class, JsonValidatingReader can be used with JsonSerializer to validate JSON while the object is being deserialized.

    跳过加载Json字符串到JObject/JArray的开销,验证Json然后将其反序列化为一个类,JsonValidatingReader可以与JsonSerializer在一个对象在反序列的时候验证Json。

    string json = @"{  'name': 'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']}";
    
    JsonTextReader reader = new JsonTextReader(new StringReader(json));
    
    JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
    validatingReader.Schema = JsonSchema.Parse(schemaJson);
    
    IList<string> messages = new List<string>();
    validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
    
    JsonSerializer serializer = new JsonSerializer();
    Person p = serializer.Deserialize<Person>(validatingReader);

    Creating JSON Schemas  生成JSON Schemas

    The simplest way to get a JsonSchema object is to load it from a string or a file.

    得到一个JsonSchema对象的最简易方法就是从字符串或者文件里加载。

    // load from a string
    JsonSchema schema1 = JsonSchema.Parse(@"{'type':'object'}");
    
    // load from a file
    using (TextReader reader = File.OpenText(@"c:schemaPerson.json"))
    {
        JsonSchema schema2 = JsonSchema.Read(new JsonTextReader(reader));
    
        // do stuff
    }

    It is also possible to create JsonSchema objects in code.

    也可以从代码里创建JsonSchema对象。

    JsonSchema schema = new JsonSchema();
    schema.Type = JsonSchemaType.Object;
    schema.Properties = new Dictionary<string, JsonSchema>
    {
        { "name", new JsonSchema { Type = JsonSchemaType.String }         },
        {
             "hobbies", new JsonSchema
            {
                Type = JsonSchemaType.Array,
                Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } }
            }
        },
    };
    
    JObject person = JObject.Parse(@"{'name': 'James','hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']}");
    
    bool valid = person.IsValid(schema);
    // true        

    原文链接:http://james.newtonking.com/json/help/index.html

    更多信息:http://json-schema.org/

  • 相关阅读:
    管理培训笔记
    Jhipster Registry(Eureka Server) Docker双向联通与高可用部署
    (转阮一峰)深入理解OAuth 2.0
    基于spring security 实现前后端分离项目权限控制
    spring security实现动态配置url权限的两种方法
    Spring Security 架构与源码分析
    开源APM系统skywalking介绍与使用
    Angular 中后台前端解决方案
    SpringBoot+Security+MyBatis+ES+MQ+Redis+Docker+Vue的电商系统
    Jenkins+GitLab+Docker+SpringCloud实现可持续自动化微服务
  • 原文地址:https://www.cnblogs.com/AlvinLiang/p/4128091.html
Copyright © 2011-2022 走看看