Home > Web Front-end > JS Tutorial > About strict verification code between json string and entity

About strict verification code between json string and entity

高洛峰
Release: 2016-12-07 10:56:06
Original
1285 people have browsed it

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;
}
Copy after login

Entity class

using System;
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreateDate { get; set; }
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template