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/

  • 相关阅读:
    iOS开发第三方库一 IQKeyboardManager
    跟着百度学PHP[14]-初识PDO数据库抽象层
    文件上传漏洞的一些总结
    逻辑漏洞挖掘入门之 简单的任意账户密码重置
    突破MIME限制上传
    关于Safe DOG的文件上传bypass
    跟着百度学PHP[13]-文件上传
    PHP flock() 函数 php中的文件锁定机制
    mysql变量
    一份不错的php面试题(附答案)(笔试题)
  • 原文地址:https://www.cnblogs.com/AlvinLiang/p/4128091.html
Copyright © 2011-2022 走看看