Strict verification code between the json string and the object.
In a project, it is required to strictly verify that the passed 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 <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);}/* 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 <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; } }
The above section describes the strict verification between json strings and entities. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!