Strict verification code between the json string and the object requires strict verification in a project that the incoming json string matches the defined class; otherwise, it is not recorded. I feel that I have found a lot of information for this strict verification, and there may be fewer people to use. I have picked it for analysis and directly posted the Code:
Using Newtonsoft. Json;
First reference Newtonsoft. Json. Schema
Main function call
Private static void Main (string [] args) {string Json = @ "{'email ': '58', 'active': true, 'createdate ': '2017-12-11 9:24:33 '}"; try {/* here, a rule is created through the specified object to verify whether the incoming json meets the requirements */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);}/* This Code is also set to catch exceptions, only for a wide range of verification, if not match, then the default value is given. The above is to strictly judge 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 ;}
Entity class
using System;public class Account{public string Email { get; set; }public bool Active { get; set; }public DateTime CreateDate { get; set; }}