首页 技术 正文
技术 2022年11月15日
0 收藏 892 点赞 3,177 浏览 3436 个字

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:\schema\Person.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/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289