给出一个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. 用代码给TABLE 添加字段,设置属性并编译

    AOTTableFieldList AOTTableFieldList ,TableFieldNode; TableName tableName = "SML_InventTableExt& ...

  2. ajax 清除缓存

    $.ajax({ url : actionUrl , beforeSend :function(xmlHttp){  // deforeSend 是请求前清除缓存  ,如果没有缓存也不使用before ...

  3. 【IHttpHandler】ASP.NET 生命周期

    对由 Microsoft® Internet 信息服务 (IIS) 处理的 Microsoft® ASP.NET 页面的每个请求都会被移交到 ASP.NET HTTP 管道.HTTP 管道由一系列托管 ...

  4. ASP.NET数据绑定

    数据绑定是ASP.NET提供的另一种访问数据库的方法.与ADO.NET数据库访问技术不同的是:数据绑定技术可以让程序员不关注数据库连接.数据库命令以及如何格式化这些数据以显示在页面上等环节,而是直接把 ...

  5. BochsDebug

    Bochs User Manual   Chapter 8. Tips and Techniques   8.12. Using Bochs internal debugger Note, if yo ...

  6. css3- border

    css3-border 1.border-color 2.border-image 3.border-radius (  none | <length>{1,4} [ / <leng ...

  7. JS匿名函数自执行函数

    JS匿名函数自执行函数:(function(){})();(function(){}) 这是一个函数,函数后面接(),则是调用函数 比如(function(arg){console.log(arg); ...

  8. SqlServer存储过程学习笔记(增删改查)

    * IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值. CREATE PROCEDURE [dbo].[PR_NewsAffiche_AddNewsEntity] ( ...

  9. C# .Net三层架构[转]

    C# .Net三层架构[转] 编写人:CC阿爸 2014-3-14 希望朋友们留下自己对三层架构的理解... 三层体系结构的概念     用户界面表示层(USL) 业务逻辑层(BLL) 数据访问层(D ...

  10. redis的lua使用(EVALSHA)

    redis 127.0.0.1:6379> SCRIPT LOAD "local list=redis.call('KEYS', KEYS[1] .. '*') return (tab ...