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/

Json.Net使用JSON Schema验证JSON格式的更多相关文章

  1. Json.Net使用JSON Schema验证JSON格式【实例】

    给出一个Json,验证其格式是否符合规则. { "coord": { //对象 "lon": 145.77, "lat": -16.92 } ...

  2. .Net使用JsonSchema验证Json

    最近项目中遇到了这样的需求,需要对上传的Json进行验证,以确保Json数据的准确性.前后使用了两种方式来验证: (1)第一种方式的实现思想:根据Json数据的格式,严格定义相应的类结构,并在Syst ...

  3. 利用JSON Schema校验JSON数据格式

    最近笔者在工作中需要监控一批http接口,并对返回的JSON数据进行校验.正好之前在某前端大神的分享中得知这个神器的存在,调研一番之后应用在该项目中,并取得了不错的效果,特地在此分享给各位读者. 什么 ...

  4. .net core json序列化首字符小写和日期格式处理

    打开Startup.cs文件,在ConfigureServices方法中添加如下代码 public void ConfigureServices(IServiceCollection services ...

  5. JSON --- 一种轻量级的数据交换格式

    目录 1. 语法 2. 解析与序列化 JSON.stringify( jsData[, filter, indent] ) JSON.parse( jsonData[, reduction]) JSO ...

  6. Go语言入门篇-jwt(json web token)权限验证

    一.token.cookie.session的区别 1.cookie Cookie总是保存在客户端中,按在客户端中的存储位置,可分为内存Cookie和硬盘Cookie. 内存Cookie由浏览器维护, ...

  7. C#如何Json转字符串;字符串转Json;Newtonsoft.Json(Json.Net)

    Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库(下载地址http://json.codeplex.com/). 下面是Json序列化和反序列化的简单封装: /// & ...

  8. 黄聪:C#如何Json转字符串;字符串转Json;Newtonsoft.Json(Json.Net)学习笔记(转)

    Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库(下载地址http://json.codeplex.com/). 下面是Json序列化和反序列化的简单封装: /// & ...

  9. c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具

    c#实例化继承类,必须对被继承类的程序集做引用   0x00 问题 类型“Model.NewModel”在未被引用的程序集中定义.必须添加对程序集“Model, Version=1.0.0.0, Cu ...

随机推荐

  1. linux设置ulimit值永久生效

    小知识的积累,转自 http://hi.baidu.com/moonelf9989/blog/item/1deadf12780fa0c5c2fd789d.html linux 默认打开文件数linux ...

  2. seafile

    ./setup-seafile-mysql.shChecking python on this machine ...  Checking python module: setuptools ... ...

  3. WWF3事件类型活动<第三篇>

    WWF将工作流分为两大类: 面向Human:在工作流运行时通过用户对外部应用程序的操作来影响工作流的业务流转. 面向System:应用程序控制流程. 工作流与应用程序都是可以单独存在的,因此它们之间的 ...

  4. 使用python脚本实现基于指定字符串的文本排序

    朋友用ansible导出了一个文件,文件中包含上千台机器的磁盘信息,他想要知道哪些机器最需要赶紧扩磁盘.思路是,按剩余磁盘空间百分数,从小到大对文本内容重新排序.下面是具体实现. 源文件ip.txt的 ...

  5. jquery+javascript编写国籍控件

    主要功能和界面介绍 国籍控件主要支持中文.英文过滤以及键盘上下事件. 源码介绍 国籍控件核心是两个文件,navtionality.js 和 mian.css.navtionality.js主要功能是国 ...

  6. 简单linux网络驱动程序

    本文代码参考<LINUX设备驱动程序>第十七章 网络驱动程序 网络地址和虚拟主机地址为: snullnet0 192.168.0.0 snullnet1 192.168.1.0 local ...

  7. POJ C++程序设计 编程题#3 编程作业—文件操作与模板

    编程题#3: 整数的输出格式 来源: POJ(Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩.) 注意: 总时间限制: 1000ms 内存限制: 1000kB 描述 利 ...

  8. Vue.js学习 Item9 – 表单控件绑定

    基础用法 可以用 v-model 指令在表单控件元素上创建双向数据绑定.根据控件类型它自动选取正确的方法更新元素.尽管有点神奇,v-model 不过是语法糖,在用户输入事件中更新数据,以及特别处理一些 ...

  9. ViewGroup 和 View 事件传递及处理小谈

    前言 在自定义组件的时候少不了会去处理一些事件相关的东西,关于事件这块网上有很多文章,有说的对的也有说的不对的,我在理解的时候也有过一段时间的迷惑,现在把自己理解的东西写下来,给有相同疑问的朋友提供些 ...

  10. 如何验证 jemalloc 优化 Nginx 是否生效

    Jemalloc 源于 Jason Evans 2006年在 BSDcan conference 发表的论文:<A Scalable Concurrent malloc Implementati ...