本文主要是介绍使用 C# 进行 JSON 反序列化实体必填项校验(webform),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用 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_type")]public string TriggerType { get; set; }/// <summary>/// 子规则/// </summary>[JsonProperty(PropertyName = "rule_combination")]public List<RuleCombination> RuleCombinations { get; set; }}/// <summary>/// 条件/// </summary>public class Condition{[JsonProperty(PropertyName = "rule_combination_id")]public string Id { get; set; }public string Parent_id { get; set; }/// <summary>/// 返回值名称/// </summary>[Required(ErrorMessage = "返回值不能为空")][JsonProperty(PropertyName = "selected_value_name")]public string SelectedValueName { get; set; }/// <summary>/// 返回值编码/// </summary>[JsonProperty(PropertyName = "selected_value_code")]public string SelectedValueCode { get; set; }/// <summary>/// 关系/// </summary>[Required(ErrorMessage = "关系不能为空")][JsonProperty(PropertyName = "trigger_type")]public string TriggerType { get; set; }/// <summary>/// 主规则/// </summary>[Required(ErrorMessage = "规则不能为空")][JsonProperty(PropertyName = "rule_combination")]public List<RuleCombination> RuleCombination { get; set; }}/// <summary>/// 根节点/// </summary>public class RootObject{[JsonProperty("id")]public string ID { get; set; }/// <summary>/// 规则名称/// </summary>[JsonProperty(PropertyName = "report_item_name")][Required(ErrorMessage = "规则名称不能为空")]public string ReportItemName { get; set; }/// <summary>/// 上报字段/// </summary>[JsonProperty(PropertyName = "report_item_code")][Required(ErrorMessage = "上报字段不能为空")]public string ReportItemCode { get; set; }/// <summary>/// 规则类型/// </summary>[JsonProperty(PropertyName = "report_item_type")][Required(ErrorMessage = "规则类型不能为空")]public string ReportType { get; set; }/// <summary>/// 默认值名称/// </summary>[JsonProperty(PropertyName = "default_value_name")]public string DefaulValueName { get; set; }/// <summary>/// 默认值编码/// </summary>[JsonProperty(PropertyName = "default_value_code")]public string DefaulValueCode { get; set; }/// <summary>/// 条件 /// </summary>[JsonProperty(PropertyName = "conditions")][Required(ErrorMessage = "返回值不能为空")]public List<Condition> Conditions { get; set; }}#endregion
反序列化和校验方法
接下来,我们需要编写方法来反序列化 JSON 并验证实体对象的必填字段。我们将递归地验证实体对象及其嵌套列表中的对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;namespace ConsoleApp1
{public class JsonValidator{// 定义递归方法用于验证 Conditions 列表public void ValidateConditions(List<Condition> conditions, ValidationContext parentContext, List<ValidationResult> validationResults, ref string errorMessageString){if (conditions != null){foreach (var condition in conditions){var conditionContext = new ValidationContext(condition, parentContext, null);Validator.TryValidateObject(condition, conditionContext, validationResults, true);// 递归验证 Condition 中的 RuleCombination 列表ValidateRuleCombinations(condition.RuleCombination, conditionContext, validationResults, ref errorMessageString);}}}// 定义递归方法用于验证 RuleCombination 列表public void ValidateRuleCombinations(List<RuleCombination> ruleCombinations, ValidationContext parentContext, List<ValidationResult> validationResults, ref string errorMessageString){if (ruleCombinations != null){foreach (var ruleCombination in ruleCombinations){var ruleCombinationContext = new ValidationContext(ruleCombination, parentContext, null);Validator.TryValidateObject(ruleCombination, ruleCombinationContext, validationResults, true);// 检查是否有验证错误if (validationResults.Count > 0){// 输出规则ID提示errorMessageString += "规则Id:" + ruleCombination.RuleId + "\r\n";// 收集并输出所有验证错误foreach (var validationResult in validationResults){foreach (var memberName in validationResult.MemberNames){errorMessageString += validationResult.ErrorMessage + "\r\n";}}// 清除当前规则的验证结果,以便处理下一个规则validationResults.Clear();}// 递归验证 RuleCombination 中的 RuleCombinations 列表ValidateRuleCombinations(ruleCombination.RuleCombinations, ruleCombinationContext, validationResults, ref errorMessageString);}}}}}
使用示例
以下是一个示例,演示如何反序列化 JSON 并使用上述方法进行验证:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApp1
{public class Program{static void Main(string[] args){string jsonNp = @"{""report_item_name"": ""名称1"",""report_item_code"": ""CM-1"",""report_item_type"": ""select"",""default_value_name"": """",""default_value_code"": """",""emr_structured_result_preprocess"": {""filter_by_time"": {""base_time_path"": ""-"",""compare_time_path"": ""-"",""offset_lower_limit"": ""-"",""offset_upper_limit"": ""-"",""time_unit"": ""-""},""sort"": {""compare_key_path"": ""-"",""sort_type"": ""-""}},""conditions"": [{""selected_value_name"": ""名称2"",""selected_value_code"": ""a"",""trigger_type"": ""all"",""rule_combination_id"": ""2"",""rule_combination"": [{""ruleId"": ""2_1"",""path"": ""2_1"",""operator"": """",""value"": ""2_1"",""type"": ""String"",""trigger_type"": """",""rule_combination"": [{""ruleId"": ""2_1_1"",""path"": """",""operator"": ""="",""value"": """",""type"": """",""trigger_type"": """",""rule_combination"": []}]}]}]
}";RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(jsonNp);JsonValidator jsonValidator = new JsonValidator();var validationResults = new List<ValidationResult>();var validationContext = new ValidationContext(rootObject, null, null);var errorMessageString = string.Empty;Validator.TryValidateObject(rootObject, validationContext, validationResults, true);// 验证 Conditions 列表jsonValidator.ValidateConditions(rootObject.Conditions, validationContext, validationResults, ref errorMessageString);if (!string.IsNullOrEmpty(errorMessageString)){Console.WriteLine("Validation failed: \r\n" + errorMessageString);}}}
}
我们首先定义了实体类并使用数据注解标记必填字段。然后,我们编写了递归验证方法,确保所有嵌套的对象都得到验证。最后,通过示例展示了如何反序列化 JSON 并进行验证。如果任何必填字段为空,则进行打印输出。结合项目实际使用,本人工作中项目是ASP.NET Web Forms , 框架是net framework 4.0
这篇关于使用 C# 进行 JSON 反序列化实体必填项校验(webform)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!