关于json字符串与实体之间的严格验证代码

一个项目中要求严格验证传入的json字符串与定义的 类匹配,否则不记录。感觉这个严格验证找了好多资料才找到,可能用的人比较少,特摘出来给大家分析,直接上代码了:

using Newtonsoft.Json;

首先引用 Newtonsoft.Json.Schema

函数调用

rush:js;"> private static void Main(string[] args) { string Json = @"{ 'Email':'58','Active':true,'CreateDate':'2015-12-11 9:24:33' }"; try { /*这里是通过指定的实体创建一个规则来验证传入的json是否符合要求*/ JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Account)); JObject person = JObject.Parse(Json); IList messages; bool valid = person.IsValid(schema,out messages); if (!valid) { foreach (string message in messages) { Console.WriteLine(message); } } else { Console.WriteLine("OK"); } } catch (JsonSerializationException ex) { Console.WriteLine(ex.Message); } /* 这段代码的也是设置捕获异常的,只是大范围的验证,如果匹配不上则给予认值。上面的是严格判断 JsonConvert.DeserializeObject(Json,new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error,Error = eventHandler }); */ Console.Read(); } public static void eventHandler(object sender,ErrorEventArgs args) { var currentError = args.ErrorContext.Error.Message; Console.WriteLine(currentError); args.ErrorContext.Handled = true; }

实体类

rush:js;"> using System; public class Account { public string Email { get; set; } public bool Active { get; set; } public DateTime CreateDate { get; set; } }

以上所述是小编给大家介绍的关于json字符串与实体之间的严格验证。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...