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

相关文章

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

使用TomCat,service输出台出现乱码的解决

《使用TomCat,service输出台出现乱码的解决》本文介绍了解决Tomcat服务输出台中文乱码问题的两种方法,第一种方法是修改`logging.properties`文件中的`prefix`和`... 目录使用TomCat,service输出台出现乱码问题1解决方案问题2解决方案总结使用TomCat,

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

JSON字符串转成java的Map对象详细步骤

《JSON字符串转成java的Map对象详细步骤》:本文主要介绍如何将JSON字符串转换为Java对象的步骤,包括定义Element类、使用Jackson库解析JSON和添加依赖,文中通过代码介绍... 目录步骤 1: 定义 Element 类步骤 2: 使用 Jackson 库解析 jsON步骤 3: 添

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

C#提取PDF表单数据的实现流程

《C#提取PDF表单数据的实现流程》PDF表单是一种常见的数据收集工具,广泛应用于调查问卷、业务合同等场景,凭借出色的跨平台兼容性和标准化特点,PDF表单在各行各业中得到了广泛应用,本文将探讨如何使用... 目录引言使用工具C# 提取多个PDF表单域的数据C# 提取特定PDF表单域的数据引言PDF表单是一

使用Python实现高效的端口扫描器

《使用Python实现高效的端口扫描器》在网络安全领域,端口扫描是一项基本而重要的技能,通过端口扫描,可以发现目标主机上开放的服务和端口,这对于安全评估、渗透测试等有着不可忽视的作用,本文将介绍如何使... 目录1. 端口扫描的基本原理2. 使用python实现端口扫描2.1 安装必要的库2.2 编写端口扫

使用Python实现操作mongodb详解

《使用Python实现操作mongodb详解》这篇文章主要为大家详细介绍了使用Python实现操作mongodb的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、示例二、常用指令三、遇到的问题一、示例from pymongo import MongoClientf