

using Newtonsoft.Json;
首先引用 Newtonsoft.Json.Schema
主函数调用
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<string> 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<Account>(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;
}实体类
using System;
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreateDate { get; set; }
}