在使用 JSON 进行数据传输时,反序列化为实体对象是常见的操作。为了确保反序列化后的对象满足业务逻辑的要求,需要对实体对象的必填字段进行校验。本文将介绍如何在非 .NET Core MVC 项目中,使用 C# 和数据注解来进行 JSON 反序列化实体的必填项校验,并实现自定义校验方法。
实体类定义
首先,定义三个实体类:RootObject、Condition 和 RuleCombination,并使用数据注解标记必填字段
#region JSONDto
/// <summary>
/// 主规则、子规则
/// </summary>
public class RuleCombination
{
[JsonProperty(PropertyName = "id")]
public string Id {
get; set; }
/// <summary>
/// 规则ruleId
/// </summary>
[JsonProperty(PropertyName = "ruleId")]
[Required(ErrorMessage = "规则ruleId不能为空")]
public string RuleId {
get; set; }
public string ConditionId {
get; set; }
public string Parent_id {
get; set; }
[Required(ErrorMessage = "路径不能为空")]
[JsonProperty(PropertyName = "path")]
public string Path {
get; set; }
[Required(ErrorMessage = "操作符不能为空")]
[JsonProperty(PropertyName = "operator")]
public string Operator {
get; set; }
[Required(ErrorMessage = "值不能为空")]
[JsonProperty(PropertyName = "value")]
public string Value {
get; set; }
/// <summary>
/// c#基础类型
/// </summary>
[Required(ErrorMessage = "类型不能为空")]
[JsonProperty(PropertyName = "type")]
public string Type {
get; set; }
/// <summary>
/// 关系
/// </summary>
[JsonProperty(PropertyName = "trigger