如何验证非预期JSON反序列化后的C# Record是否有效?
C# Record反序列化后检查实例有效性的方案
当用System.Text.Json反序列化不匹配的JSON到MyRecord类型时,只要JSON是合法的对象结构,哪怕没有目标属性,序列化器都会创建一个属性为默认值(字符串为空)的实例,不会返回null。以下几种方法可以检查实例是否有效:
1. 直接检查必填属性
因为你的MyRecord的EndPoint和Id都是必填的字符串,直接判断这两个属性是否不为空即可:
var myType = JsonSerializer.Deserialize<MyRecord>(jsonStr, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); bool isValid = myType != null && !string.IsNullOrEmpty(myType.EndPoint) && !string.IsNullOrEmpty(myType.Id); if (!isValid) { // 执行无效实例的处理逻辑 }
2. 给Record内置验证方法
在Record里添加一个验证方法,集中处理有效性判断:
public record MyRecord(string EndPoint, string Id) { public bool IsValid() { return !string.IsNullOrEmpty(EndPoint) && !string.IsNullOrEmpty(Id); } } // 调用示例 var myType = JsonSerializer.Deserialize<MyRecord>(jsonStr, options); if (myType == null || !myType.IsValid()) { // 处理无效情况 }
3. 启用严格反序列化(.NET 6+)
通过JsonSerializerOptions的DisallowExtraProperties选项,让JSON包含多余属性时直接抛出异常,再结合属性检查:
try { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, DisallowExtraProperties = true // JSON有多余属性时抛出JsonException }; var myType = JsonSerializer.Deserialize<MyRecord>(jsonStr, options); if (myType == null || string.IsNullOrEmpty(myType.EndPoint) || string.IsNullOrEmpty(myType.Id)) { // 处理属性为空的无效实例 } } catch (JsonException) { // 处理JSON结构不匹配的情况 }
注意:这个选项只拦截多余属性,若JSON缺少必填属性,还是会生成默认值实例,所以需要配合属性检查。
4. 用数据注解做验证
给Record的属性添加[Required]注解,借助Validator类做验证:
using System.ComponentModel.DataAnnotations; public record MyRecord([Required] string EndPoint, [Required] string Id); // 验证示例 var myType = JsonSerializer.Deserialize<MyRecord>(jsonStr, options); if (myType == null) { // 处理null情况 } else { var validationContext = new ValidationContext(myType); var validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(myType, validationContext, validationResults, validateAllProperties: true); if (!isValid) { // 可通过validationResults查看具体错误信息,再处理无效情况 } }
内容的提问来源于stack exchange,提问作者auburg
相关产品推荐
相关产品推荐

