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. 使用fiddler2抓取手机发出的请求信息

    fiddler2 简介:抓包软件,可以替换服务器js,从而实现本地调试 初始化设置: 1.工具——fiddler选项——常规——允许远程计算机连接(打钩)     2.按下图设置   3.设置连接,如 ...

  2. myeclipse上SVN代码合并详细步骤图解

    1.  在装有svn插件的myeclipse中,在主干上选择需要合并的文件或文件夹 右击 -> 合并(merge) 2. 选择合并类型--合并两个不同的树 Merge -> Next 3. ...

  3. 基于IIS的HTTP、FTP文件服务器搭建与性能测试

    鉴于CAPI中文件操作是非常重要的一环,为了提高性能,直接提供下载地址供客户端下载: 1.基于IIS的HTTP文件服务器.FTP文件服务器(为了减少因编码造成的性能问题,尽量不要在文件服务器上写代码) ...

  4. Android IOS WebRTC 音视频开发总结(十二)-- sufaceview

    谈到音视频不得不谈谈对视频呈现的理解,为了让大家能有一个更好的理解,先看看android里面SurfaceView的原理,后续陆续分享其绘画原理. 说明:本文是转载的,转载自哪里我也不知道,貌似经过很 ...

  5. android中关闭软键盘

    /**隐藏软键盘**/ View view = getWindow().peekDecorView(); if (view != null) { InputMethodManager inputman ...

  6. IOS多线程(一)

    一.绪论 1.进程:平时看到的一个应用程序,即可算作一个线程. 每个进程都有一个PID作为进程ID,有一个Process Name作为进程名字等. 2.线程:一个进程可以有多个线程,而每个线程只可属于 ...

  7. winform之excel导入和导出

    引用命名空间   using Microsoft.Office.Interop.Excel;DataGridView 导出到Excel public static void SaveAs(DataGr ...

  8. mariadb介绍

    事务(Transaction):组织多个操作为一个整体,要么全部执行,要么全部不执行 “回滚” ,rollback SQL接口:sql语句分析器和优化器 表:为了满足范式设计要求,将一个数据集分拆为多 ...

  9. php5.5新函数array_column

    php5.5新增了一个新的数组函数,感觉挺使用的,低版本的实现按照如下实现 if(!function_exists('array_column')){ function array_column($i ...

  10. android 模拟按键事件

    模拟按键事件可以提高代码的复用性,比如在一个edittext的回车事件里做的一些处理 在该edittext的另一个输入要做相同的处理时,模拟按键事件就非常方便了. 代码很简单,直接上代码: new T ...