C# JsonSerializer反序列化时RafSpecialAccount部分属性为null
问题根因
三个字段反序列化为null的核心原因是待解析JSON中对应字段的键名末尾包含多余的尾部空格:
specialAccountFinancialInstitutionAddress(键名末尾多1个半角空格)specialAccountOpenDate(键名末尾多1个半角空格)specialAccountClosedDate(键名末尾多1个半角空格)
你当前使用的System.Text.Json序列化器,即便开启了PropertyNameCaseInsensitive = true的大小写不敏感配置,默认匹配逻辑仍然会将空格视为有效字符参与比对,因此带尾部空格的JSON键无法和C#类中无空格的属性名完成映射,最终这三个属性就会被赋值为默认值null。
修复方案
根据你是否能修改上游生成的JSON源数据,二选一即可:
方案1:修正源JSON(优先推荐)
直接删除JSON中上述三个键名末尾的多余空格,不需要调整任何C#反序列化代码和类定义,现有逻辑即可正常完成字段映射。
方案2:适配带空格的JSON键(无法修改源JSON时使用)
如果上游JSON格式无法调整,直接给RafSpecialAccount类中对应的三个属性添加JsonPropertyName特性,显式指定匹配带尾部空格的键名即可,修改后的类定义片段如下:
public class RafSpecialAccount { public string specialAccountClientNumber { get; set; } public string specialAccountNumber { get; set; } public string specialAccountFinancialInstitutionName { get; set; } [JsonPropertyName("specialAccountFinancialInstitutionAddress ")] public string specialAccountFinancialInstitutionAddress { get; set; } [JsonPropertyName("specialAccountOpenDate ")] public string specialAccountOpenDate { get; set; } [JsonPropertyName("specialAccountClosedDate ")] public string specialAccountClosedDate { get; set; } public string specialAccountAmount { get; set; } }
如果后续可能出现其他JSON键带前后空格的情况,也可以自定义实现JsonNamingPolicy,在属性名匹配逻辑中统一对JSON键做首尾空格裁剪,一劳永逸处理同类问题。
额外提醒:你贴出的
convertJSONToString方法代码不完整,反序列化逻辑执行后没有拼接返回值,属于独立的代码疏漏,和本次字段映射为null的问题无关。
内容的提问来源于stack exchange,提问作者bigrouss
相关产品推荐
相关产品推荐

