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

相关文章

使用Dify访问mysql数据库详细代码示例

《使用Dify访问mysql数据库详细代码示例》:本文主要介绍使用Dify访问mysql数据库的相关资料,并详细讲解了如何在本地搭建数据库访问服务,使用ngrok暴露到公网,并创建知识库、数据库访... 1、在本地搭建数据库访问的服务,并使用ngrok暴露到公网。#sql_tools.pyfrom

使用mvn deploy命令上传jar包的实现

《使用mvndeploy命令上传jar包的实现》本文介绍了使用mvndeploy:deploy-file命令将本地仓库中的JAR包重新发布到Maven私服,文中通过示例代码介绍的非常详细,对大家的学... 目录一、背景二、环境三、配置nexus上传账号四、执行deploy命令上传包1. 首先需要把本地仓中要

Spring Cloud之注册中心Nacos的使用详解

《SpringCloud之注册中心Nacos的使用详解》本文介绍SpringCloudAlibaba中的Nacos组件,对比了Nacos与Eureka的区别,展示了如何在项目中引入SpringClo... 目录Naacos服务注册/服务发现引⼊Spring Cloud Alibaba依赖引入Naco编程s依

Java springBoot初步使用websocket的代码示例

《JavaspringBoot初步使用websocket的代码示例》:本文主要介绍JavaspringBoot初步使用websocket的相关资料,WebSocket是一种实现实时双向通信的协... 目录一、什么是websocket二、依赖坐标地址1.springBoot父级依赖2.springBoot依赖

Java使用Mail构建邮件功能的完整指南

《Java使用Mail构建邮件功能的完整指南》JavaMailAPI是一个功能强大的工具,它可以帮助开发者轻松实现邮件的发送与接收功能,本文将介绍如何使用JavaMail发送和接收邮件,希望对大家有所... 目录1、简述2、主要特点3、发送样例3.1 发送纯文本邮件3.2 发送 html 邮件3.3 发送带

Nginx如何进行流量按比例转发

《Nginx如何进行流量按比例转发》Nginx可以借助split_clients指令或通过weight参数以及Lua脚本实现流量按比例转发,下面小编就为大家介绍一下两种方式具体的操作步骤吧... 目录方式一:借助split_clients指令1. 配置split_clients2. 配置后端服务器组3. 配

使用DeepSeek搭建个人知识库(在笔记本电脑上)

《使用DeepSeek搭建个人知识库(在笔记本电脑上)》本文介绍了如何在笔记本电脑上使用DeepSeek和开源工具搭建个人知识库,通过安装DeepSeek和RAGFlow,并使用CherryStudi... 目录部署环境软件清单安装DeepSeek安装Cherry Studio安装RAGFlow设置知识库总

SpringBoot接收JSON类型的参数方式

《SpringBoot接收JSON类型的参数方式》:本文主要介绍SpringBoot接收JSON类型的参数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、jsON二、代码准备三、Apifox操作总结一、JSON在学习前端技术时,我们有讲到过JSON,而在

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Spring-AOP-ProceedingJoinPoint的使用详解

《Spring-AOP-ProceedingJoinPoint的使用详解》:本文主要介绍Spring-AOP-ProceedingJoinPoint的使用方式,具有很好的参考价值,希望对大家有所帮... 目录ProceedingJoinPoijsnt简介获取环绕通知方法的相关信息1.proceed()2.g