在一个项目中要求严格验证传入的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 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。