给出一个Json,验证其格式是否符合规则。

{
"coord": {                                 //对象
"lon": 145.77,
"lat": -16.92
},
"sys": {                                  //对象
"type": ,
"id": ,
"message": 0.0402,
"country": "AU",
"sunrise": ,
"sunset":
},
"weather": [                                //数组(子项是对象)
{
"id": ,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
},
{
"id": ,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "cmc stations",                          //字符串
"main": {                                  //对象
"temp": 304.15,                               //浮点型
"pressure": ,                              //整形
"humidity": ,                               //整形
"temp_min": 304.15,
"temp_max": 304.15
},
"wind": {                                  //对象
"speed": 5.7,
"deg":
},
"clouds": {
"all":
},
"dt": ,                              //整形
"id": ,                                //整形
"name": "Cairns",                              //字符串
"cod": 200                                  //整形
}

在前一篇文中我们知道JSON Schema可以通过加载字符串或者文件得到,可是新手一下子写出验证的字符串实在有点难度。

还好,Json.Net里面可以在代码里创建JSON Schema,简直是手把手教学,显浅易懂。

参见上一篇文中的代码里创建JSON Schema,我们将这个Json分拆为coord、sys、weather、base、main、wind、clouds、dt等等小的json,逐一创建对应的模式,最后组合在一起验证完整的Json。

            JsonSchema coordSchema = new JsonSchema();
coordSchema.Type = JsonSchemaType.Object;
coordSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "lon", new JsonSchema { Type = JsonSchemaType.Float } },
{ "lat", new JsonSchema { Type = JsonSchemaType.Float } }
}; JsonSchema sysSchema = new JsonSchema();
sysSchema.Type = JsonSchemaType.Object;
sysSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "type", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "id", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "message", new JsonSchema { Type = JsonSchemaType.Float } },
{ "country", new JsonSchema { Type = JsonSchemaType.String } },
{ "sunrise", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "sunset", new JsonSchema { Type = JsonSchemaType.Integer } }
}; JsonSchema weatherItemSchema = new JsonSchema();
weatherItemSchema.Type = JsonSchemaType.Object;
weatherItemSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "id", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "main", new JsonSchema { Type = JsonSchemaType.String } },
{ "description", new JsonSchema { Type = JsonSchemaType.String } },
{ "icon", new JsonSchema { Type = JsonSchemaType.String } }
}; JsonSchema windSchema = new JsonSchema();
windSchema.Type = JsonSchemaType.Object;
windSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "speed", new JsonSchema { Type = JsonSchemaType.Float } },
{ "deg", new JsonSchema { Type = JsonSchemaType.Integer } }
}; JsonSchema weatherSchema = new JsonSchema();
weatherSchema.Type = JsonSchemaType.Array;
weatherSchema.Items = new List<JsonSchema>();
weatherSchema.Items.Add(weatherItemSchema); JsonSchema mainSchema = new JsonSchema();
mainSchema.Type = JsonSchemaType.Object;
mainSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "temp", new JsonSchema { Type = JsonSchemaType.Float } },
{ "pressure", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "humidity", new JsonSchema { Type = JsonSchemaType.Integer } },
{ "temp_min", new JsonSchema { Type = JsonSchemaType.Float } },
{ "temp_max", new JsonSchema { Type = JsonSchemaType.Float } }
}; JsonSchema cloudsSchema = new JsonSchema();
cloudsSchema.Type = JsonSchemaType.Object;
cloudsSchema.Properties = new Dictionary<string, JsonSchema>
{
{ "all", new JsonSchema { Type = JsonSchemaType.Float } }
};

最后将这些分支的模式组合起来:

            JsonSchema schema = new JsonSchema();
schema.Type = JsonSchemaType.Object;
schema.Properties = new Dictionary<string, JsonSchema>
{
{"coord", coordSchema },
{"sys", sysSchema },
{"weather",weatherSchema},
{"base", new JsonSchema{Type = JsonSchemaType.String} },
{"main",mainSchema},
{"wind",windSchema},
{"clouds",cloudsSchema},
{"dt", new JsonSchema{Type = JsonSchemaType.Integer} },
{"id", new JsonSchema{Type = JsonSchemaType.Integer} },
{"name", new JsonSchema{Type = JsonSchemaType.String} },
{"cod", new JsonSchema{Type = JsonSchemaType.Integer} }
};
bool valid = jobject.IsValid(schema);

也可以将最后的schema转化为字符串保存在专门的文件里,需要的时候从中读取:

{
"type": "object",
"properties": {
"coord": {
"type": "object",
"properties": {
"lon": {
"type": "number"
},
"lat": {
"type": "number"
}
}
},
"sys": {
"type": "object",
"properties": {
"type": {
"type": "integer"
},
"id": {
"type": "integer"
},
"message": {
"type": "number"
},
"country": {
"type": "string"
},
"sunrise": {
"type": "integer"
},
"sunset": {
"type": "integer"
}
}
},
"weather": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"main": {
"type": "string"
},
"description": {
"type": "string"
},
"icon": {
"type": "string"
}
}
}
},
"base": {
"type": "string"
},
"main": {
"type": "object",
"properties": {
"temp": {
"type": "number"
},
"pressure": {
"type": "integer"
},
"humidity": {
"type": "integer"
},
"temp_min": {
"type": "number"
},
"temp_max": {
"type": "number"
}
}
},
"wind": {
"type": "object",
"properties": {
"speed": {
"type": "number"
},
"deg": {
"type": "integer"
}
}
},
"clouds": {
"type": "object",
"properties": {
"all": {
"type": "number"
}
}
},
"dt": {
"type": "integer"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"cod": {
"type": "integer"
}
}
}

验证说明:

1、原Json字符串,正确;

2、原Json的weather列表增加{"id": 801,"main": "Clouds","description": "few clouds","icon": "02d"},正确;

3、原Json的id修改为haha,错误;

4、原Json增加"planet":earth,错误,增加了额外的结构;

5、原Json删除"id": 2172797,  "cod": 200,正确

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

  1. Json.Net使用JSON Schema验证JSON格式

    Json.NET supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. It s ...

  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. navicat 连接oracle

    Navicat远程连接oracle数据库数据库需要设置一下oci.dll. 下面介绍如何进行设置. 工具/原料   Navicat Pre instantclient-basiclite-nt-12. ...

  2. 理解Linux启动过程

    传统的Linux系统启动过程主要由著名的init进程(也被称为SysV init启动系统)处理,而基于init的启动系统被认为有效率不足的问题,systemd是Linux系统机器的另一种启动方式,宣称 ...

  3. MySQL 按日期分表

    一.表不存在时则创建 之前做项目实在是太赶了,很多东西都没记录.是时候补回来了 MySQL做一个大表,由于要存历史记录,所以数据量很大,查询很慢.恰好查询的时候,又不需要时间太久的冷数据.现在将其实现 ...

  4. C# 共用的返回数据类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Dscf ...

  5. Android IOS WebRTC 音视频开发总结(二三)-- hurtc使用说明

    本文主要介绍如何测试基于浏览器和手机的视频通话程序,转载请说明出处,文章来自博客园RTC.Blacker,更多详见www.blackerteam.com   很多人想测试浏览器(包括浏览器版本和桌面e ...

  6. hdu 2255 奔小康赚大钱 KM算法

    看到这么奇葩的题目名我笑了,后来这么一个裸的KM调了2小时我哭了…… 这是个裸的KM算法,也没什么多说的,主要是注意多组数据时,每次都要把各种数组清空啊,赋值啊什么的,反正比较麻烦.至于为什么调了2小 ...

  7. NASM编译器的$和$$标记

    NASM中的times相当于MASM中的dup起到重复定义的作用. $表示当前行的偏移地址,$$表示当前段的起始偏移地址, ;------------------------------------- ...

  8. -webkit-filter属性用来干什么

    这两天有看到国外网站纷纷介绍-webkit-filter,开始很迷惑,丫是想要学IE吗?今天看了下,和IE的滤镜没一毛关系啊,而且,效果很赞! 这些滤镜效果最初是用于SVG的,W3C引入到CSS中,然 ...

  9. firefox 中碰到的一个小坑

    情况描述: 在一个处于正常文档流的div中,里面有一部分文字,还有个有浮动的块, 上代码 HTML: <div class="container">   this is ...

  10. 小鸟哥哥博客 For SAE

    独立博客地址:http://www.zhujiawei.com.cn/ 辞职后出去玩了几个月,把积蓄都快花光了,打算熬到年底再找工作.最近闲来无聊,想起自己一年前趁着活动便宜,一口气买了10年的域名一 ...