使用 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

相关文章

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

QT进行CSV文件初始化与读写操作

《QT进行CSV文件初始化与读写操作》这篇文章主要为大家详细介绍了在QT环境中如何进行CSV文件的初始化、写入和读取操作,本文为大家整理了相关的操作的多种方法,希望对大家有所帮助... 目录前言一、CSV文件初始化二、CSV写入三、CSV读取四、QT 逐行读取csv文件五、Qt如何将数据保存成CSV文件前言

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代