关于json字符串与实体之间的严格验证代码
在一个项目中要求严格验证传入的json字符串与定义的类匹配,否则不记录。感觉这个严格验证找了好多资料才找到,可能用的人比较少,特摘出来给大家分析,直接上代码了:
usingNewtonsoft.Json;
首先引用Newtonsoft.Json.Schema
主函数调用
privatestaticvoidMain(string[]args)
{
stringJson=@"{
'Email':'58',
'Active':true,
'CreateDate':'2015-12-119:24:33'
}";
try
{
/*这里是通过指定的实体创建一个规则来验证传入的json是否符合要求*/
JSchemaGeneratorgenerator=newJSchemaGenerator();
JSchemaschema=generator.Generate(typeof(Account));
JObjectperson=JObject.Parse(Json);
IList<string>messages;
boolvalid=person.IsValid(schema,outmessages);
if(!valid)
{
foreach(stringmessageinmessages)
{
Console.WriteLine(message);
}
}
else
{
Console.WriteLine("OK");
}
}
catch(JsonSerializationExceptionex)
{
Console.WriteLine(ex.Message);
}
/*
这段代码的也是设置捕获异常的,只是大范围的验证,如果匹配不上则给予默认值。上面的是严格判断
JsonConvert.DeserializeObject<Account>(Json,newJsonSerializerSettings
{
MissingMemberHandling=MissingMemberHandling.Error,
Error=eventHandler
});
*/
Console.Read();
}
publicstaticvoideventHandler(objectsender,ErrorEventArgsargs)
{
varcurrentError=args.ErrorContext.Error.Message;
Console.WriteLine(currentError);
args.ErrorContext.Handled=true;
}
实体类
usingSystem;
publicclassAccount
{
publicstringEmail{get;set;}
publicboolActive{get;set;}
publicDateTimeCreateDate{get;set;}
}
以上所述是小编给大家介绍的关于json字符串与实体之间的严格验证,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!