Newtonsoft JSON反序列化异常:必填属性存在却提示未找到
Newtonsoft.Json反序列化必填属性存在却报错的解决方法
使用Newtonsoft.Json进行反序列化时,明明JSON中存在Customer Name属性,却抛出JsonSerializationException提示必填属性'Customer Name'未找到。
问题相关代码与信息
待反序列化的JSON(原JSON存在语法错误,已修正)
{ "docType": "payment-remittance-v1.4", "fields": { "Customer Name": { "type": "string", "valueString": "xxx", "spans": [ { "offset": 284, "length": 43 } ] }, "Payment Reference": { "type": "string", "valueString": "3875014846", "content": "3875014846", "confidence": 0.92, "spans": [ { "offset": 167, "length": 10 } ] }, "Remittance Date": { "type": "date", "content": "16.02.2023", "confidence": 0.97, "spans": [ { "offset": 180, "length": 10 } ] } }, "confidence": 0.125, "spans": [ { "offset": 0, "length": 1048 } ] }
对应的C#实体类
public class PredictionFields { [JsonProperty("Customer Name", Required = Required.Always)] public BaseField CustomerName { get; set; } [JsonProperty("Payment Reference", Required = Required.Always)] public BaseField PaymentReference { get; set; } } public class BaseField { [JsonProperty("confidence")] public double Confidence { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("valueNumber")] public double ValueNumber { get; set; } [JsonProperty("valueString")] public string ValueString { get; set; } [JsonProperty("content")] public string Content { get; set; } // 可选:添加spans属性定义以匹配JSON结构 [JsonProperty("spans")] public List<Span> Spans { get; set; } } public class Span { [JsonProperty("offset")] public int Offset { get; set; } [JsonProperty("length")] public int Length { get; set; } } public class Document { [JsonProperty("docType")] public string DocType { get; set; } [JsonProperty("fields")] public PredictionFields Fields { get; set; } [JsonProperty("confidence")] public double Confidence { get; set; } // 可选:添加spans属性定义 [JsonProperty("spans")] public List<Span> Spans { get; set; } }
报错信息
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Required property 'Customer Name' not found in JSON. Path 'fields', line 82, position 3.
问题原因
原JSON存在多余的尾逗号("Remittance Date"对象末尾的逗号),属于无效JSON语法。虽然部分解析器兼容尾逗号,但Newtonsoft.Json解析此类无效JSON时会出现结构解析异常,进而误判必填属性Customer Name不存在。
解决步骤
- 修复JSON语法错误:移除所有属性/数组元素末尾的多余逗号,确保JSON格式合法。
- 可选补全实体类属性:如果需要保留JSON中的
spans数据,在BaseField和Document类中添加Span实体类及对应属性定义,避免数据丢失。
修复后重新执行反序列化操作,即可正常识别Customer Name属性,解决报错问题。
内容的提问来源于stack exchange,提问作者Brendan Gooden
相关产品推荐
相关产品推荐

