Strict verification code between json strings and entities

Source: Internet
Author: User
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; }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.