In a project, it is required to strictly verify that the incoming json string matches the defined class, otherwise it will not be recorded. I feel that this strict verification required a lot of information to find. It may be used by relatively few people, so I extracted it for everyone to analyze and put it directly into the code:
using Newtonsoft.Json;
First quote Newtonsoft.Json.Schema
Master Function call
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; }
Entity class
using System; public class Account { public string Email { get; set; } public bool Active { get; set; } public DateTime CreateDate { get; set; } }