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

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

{
  "coord": {                                 //对象
    "lon": 145.77,
    "lat": -16.92
  },
  "sys": {                                  //对象
    "type": 1,
    "id": 8166,
    "message": 0.0402,
    "country": "AU",
    "sunrise": 1417116823,
    "sunset": 1417163764
  },
  "weather": [                                //数组(子项是对象)
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    },
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    }
  ],
  "base": "cmc stations",                          //字符串
  "main": {                                  //对象
    "temp": 304.15,                               //浮点型
    "pressure": 1012,                              //整形
    "humidity": 43,                               //整形
    "temp_min": 304.15,
    "temp_max": 304.15
  },
  "wind": {                                  //对象
    "speed": 5.7,
    "deg": 110
  },
  "clouds": {
    "all": 20
  },
  "dt": 1417134600,                              //整形
  "id": 2172797,                                //整形
  "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,正确

时间: 2024-08-28 04:30:19

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

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

Json.NET supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. It sits under the Newtonsoft.Json.Schema namespace. Json.NET通过JsonSchema和JsonValidatingReader类,支持JSON Schema标准.这两个类位于Newtonsoft.Json.Schema命名空间. JSON Sche

.Net使用JsonSchema验证Json

最近项目中遇到了这样的需求,需要对上传的Json进行验证,以确保Json数据的准确性.前后使用了两种方式来验证: (1)第一种方式的实现思想:根据Json数据的格式,严格定义相应的类结构,并在System.Runtime.Serialization命名空间下的DataContractAttribute.DataMemberAttribute对class和property进行标注,如果property是必须提供的,则在Property上添加[DataMember(IsRequired = true

Ajax datatype:&#39;JSON&#39;的error问题Status1:200,JSON格式

转自:http://blog.sina.com.cn/s/blog_6e001be701017rux.html <script src="../js/jquery-1.8.0-vsdoc.js" type="text/javascript"></script> JSON格式有误,jquery 1.4以后的json格式变严格了,需注意: 必须要这种格式 {"键":"值","键":&qu

Android Json解析简单高效之org.json,取值如囊中取物

我们通常在Android上采用Gson来解析Json数据,很方便的就可以把数据转换成List或者map.当碰到日期时间的时候,你可能会遇到坑,需要格式化一下日期时间格式. 本文介绍org.json这种不需要导入任何包的解析方式,不管Json多少层,如探囊取物. 1.解析{"":""} 格式的 JSONObject 如何确认是这种格式,我们都不需要看,打开 http://json.cn (Json在线解析及格式化验证网站),把Json数据直接粘贴到左边,如果是正确的J

使用Json.Net解决MVC中各种json操作

最近收集了几篇文章,用于替换MVC中各种json操作,微软mvc当然用自家的序列化,速度慢不说,还容易出问题,自定义性也太差,比如得特意解决循环引用的问题,比如datetime的序列化格式,比如性能.NewtonSoft.json也就是Json.Net性能虽然不是最好的,但是是比较靠前的,其功能是最强大的,包含各种json操作模式.现在来看看mvc中的替换1, Controller.Json方法这个方法最容易出现循环引用,比如EF查出一个一对多集合想序列化,结果a引用了子表b,b中还引用了a,导

json与jsonp区别浅析(json才是目的,jsonp只是手段) (转)

一言以蔽之,json返回的是一串数据:而jsonp返回的是脚本代码(包含一个函数调用): JSON其实就是JavaScript中的一个对象,跟var obj={}在质上完全一样,只是在量上可以无限扩展.简单地讲,json其实就是JavaScript中的对象(Object)和数组(Array,其实也是对象)这倆好基友在那儿你嵌我我嵌你地套上n多层,以此模拟出许多复杂的数据结构. json易于人阅读和编写,也易于机器解析和生成,相对网络传输速率较高,功能型网站前后端往往要频繁大量交换数据,而json

JSON对象和字符串之间的相互转换JSON.stringify(obj)和JSON.parse(string)

在Firefox,chrome,opera,safari,ie9,ie8等高级浏览器直接可以用JSON对象的stringify()和parse()方法. JSON.stringify(obj)将JSON转为字符串.JSON.parse(string)将字符串转为JSON格式: var a={"name":"tom","sex":"男","age":"24"}; var aToStr =

JSon SuperObject 研究2:数据集与JSON对象互转

JSon SuperObject 研究2:数据集与JSON对象互转 JSON不能完全替代XML,但绝对是未来的大势所趋,其优点是简单.体积小.解析更快.解析占用资源更少.在delphi中,数据集是最常用数据存取方式.因此,必须建立JSON与TDataSet之间的互转关系,实现数据之间通讯与转换.值得注意的是,这只是普通的TDataset与JSON之间转换,由于CDS包含了Delta数据包,其数据格式远比普通的TDataset更复杂.下面的程序,或许你有不同的想法,如果你的想法更好更快,欢迎一起讨

JSON入门之二:org.json的基本使用方法

java中用于解释json的主流工具有org.json.json-lib与gson.本文介绍org.json的应用. 官方文档: http://www.json.org/java/ http://developer.android.com/reference/org/json/package-summary.html 1.主要类 Classes JSONArray A dense indexed sequence of values. JSONObject A modifiable set of