给出一个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. chrome浏览器设置小于12号的字体不起作用?

    在某些chrome浏览器下,css里设置的10号字体竟然不起作用!仍显示12号大小,对比firefox.ie6.7.8.9,他们的显示都是好的. 要是你也碰到这问题,可以这样解决: -webkit-t ...

  2. 【Linux】Centos部署MySQL

    将CentOS部署MySQL需要本地配置环境.本地编译MySQL,耗时较长的情况,优化为编译成型MySQL并打包,推送并按配置部署. 首先需要在一台机器配置好环境,搭个YUM源,并将所需要的包取出备用 ...

  3. gulp&gulp-less

    使用gulp-less插件将less文件编译成css,当有less文件发生改变自动编译less,并保证less语法错误或出现异常时能正常工作并提示错误信息. 1.本地安装gulp-less githu ...

  4. 深入理解JavaScript系列(转自汤姆大叔)

    深入理解JavaScript系列文章,包括了原创,翻译,转载,整理等各类型文章,如果对你有用,请推荐支持一把,给大叔写作的动力. 深入理解JavaScript系列(1):编写高质量JavaScript ...

  5. Longest Common Prefix [LeetCode 14]

    1- 问题描述 Write a function to find the longest common prefix string amongst an array of strings. 2- 思路 ...

  6. phalcon框架学习之view

    phalcon框架的view分多级:全局-控制器视图-动作视图.视图由上到下,按层级嵌套. 全局视图 默认全局视图为Views/index.html,所有的页面展示时,默认调用此页面,在这个页面中必须 ...

  7. slf4j+log4j配置

    下载三个包: 三个包分别是:log4j的API包,slf4j的API包,slf4j对log4j的适配包. 选择使用slf4j一个重要的原因是支持占位符{},不用频繁操作字符串对象. 实现代码如下: i ...

  8. html/css 关于脱离文档流的几种情况

    所谓的文档流 顾名思义就是按照顺序流下来,指的是html元素从上往下 从左往右的流式排列, 比如说写了5个Div,正常的文档流是依次显示这5个div块: 脱离文档流就是指它所显示的位置和文档代码就不一 ...

  9. C#反射动态调用dll中的方法

    //加载程序集(dll文件地址),使用Assembly类 Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirec ...

  10. Environment类,获取程序所在机器信息

    一.属性 CommandLine  获取该进程的命令行.CurrentDirectory 获取或设置当前工作目录的完全限定路径.ExitCode 获取或设置进程的退出代码.HasShutdownSta ...