使用Form Recognizer V3自定义模型提取表格数据遇空值问题求助(C#/.NET6)
解决Form Recognizer自定义模型表格字段返回null的问题
必须对表格类型的字段做特殊处理。自定义模型中逐单元格标注的表格,在解析后会被组织为List包含Dictionary的复杂结构,而DocumentField.Content属性仅适用于字符串、数字等简单类型,复杂类型的Content会直接返回null,因此必须通过Value属性逐层访问内部数据。
修改原代码,加入字段类型判断逻辑,针对表格字段做专门解析:
AzureKeyCredential azureKey = new(_formRecognizerKey); DocumentAnalysisClient analysisClient = new(new Uri(_formRecognizerEndPoint), azureKey); AnalyzeDocumentOperation analyzeDocumentOperation = await analysisClient.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, _formRecognizerCustomModelId, new Uri(urlblob)); AnalyzeResult result = analyzeDocumentOperation.Value; foreach (AnalyzedDocument document in result.Documents) { foreach (KeyValuePair<string, DocumentField> fieldKvp in document.Fields) { string fieldName = fieldKvp.Key; DocumentField field = fieldKvp.Value; string fieldValue = string.Empty; float confidence = field.Confidence; // 根据字段类型处理取值逻辑 switch (field.FieldType) { case DocumentFieldType.String: fieldValue = field.Value.AsString(); break; case DocumentFieldType.List: // 处理自定义模型标注的表格数据 var tableRows = field.Value.AsList(); List<string> rowContents = new(); foreach (var rowField in tableRows) { if (rowField.FieldType == DocumentFieldType.Dictionary) { var cells = rowField.Value.AsDictionary(); // 拼接当前行的所有单元格内容,格式可根据业务调整 string rowContent = string.Join(" | ", cells.Select(c => $"{c.Key}: {c.Value.Content ?? c.Value.Value.ToString()}")); rowContents.Add(rowContent); } } fieldValue = string.Join(Environment.NewLine, rowContents); break; // 可根据业务需求添加其他类型的处理(如数字、日期等) default: fieldValue = field.Content ?? field.Value.ToString(); break; } response.DocumentsFields.Add(new DocumentFieldResult { Key = fieldName, Values = fieldValue, Confidence = confidence }); } }
关键处理说明:
- 表格字段的
FieldType为List,需调用field.Value.AsList()获取所有行数据 - 每行数据是
Dictionary类型,键为你标注的单元格标签,值为对应单元格的DocumentField对象 - 可根据业务需求调整表格数据的输出格式,比如转换为结构化的列表对象,而非拼接字符串
- 简单类型字段直接通过
AsString()、AsFloat()等强类型方法取值,避免依赖Content属性导致的空值问题
内容的提问来源于stack exchange,提问作者Alberto Smith
相关产品推荐
相关产品推荐

