使用 C# 进行 JSON 反序列化实体必填项校验(webform)

2024-06-21 16:28

本文主要是介绍使用 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)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081730

相关文章

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令