如何将Azure Vision输出的JSON字符串转换回原OCR结果对象?
问题解答:Azure计算机视觉OCR结果对象的JSON序列化与反序列化
可以将Azure计算机视觉返回的OCR结果对象序列化为JSON字符串后,再反序列化回原类型对象。
原因说明
Azure认知服务计算机视觉SDK中的ReadOperationResult、AnalyzeResult、ReadResult、Line等核心模型类都是标准的POCO(Plain Old CLR Object)类,默认支持JSON序列化/反序列化——类属性与JSON字段一一对应,无特殊序列化障碍。结合你代码中已引用的Newtonsoft.Json库,即可完成双向转换。
代码示例(基于你的快速入门代码修改)
在ReadFileUrl方法中,获取到results对象后,添加序列化和反序列化逻辑:
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("READ FILE FROM URL"); Console.WriteLine(); // 原有的读取文本逻辑 var textHeaders = await client.ReadAsync(urlFile); string operationLocation = textHeaders.OperationLocation; Thread.Sleep(2000); const int numberOfCharsInOperationId = 36; string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId); ReadOperationResult results; Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}..."); Console.WriteLine(); do { results = await client.GetReadResultAsync(Guid.Parse(operationId)); } while ((results.Status == OperationStatusCodes.Running || results.Status == OperationStatusCodes.NotStarted)); // --- 新增:将结果序列化为JSON字符串 --- string jsonResult = JsonConvert.SerializeObject(results, Formatting.Indented); Console.WriteLine("序列化后的JSON字符串:"); Console.WriteLine(jsonResult); // --- 新增:将JSON字符串反序列化回原对象 --- ReadOperationResult deserializedResult = JsonConvert.DeserializeObject<ReadOperationResult>(jsonResult); // 验证反序列化后的对象可用性 Console.WriteLine("\n反序列化后提取的文本内容:"); foreach (ReadResult page in deserializedResult.AnalyzeResult.ReadResults) { foreach (Line line in page.Lines) { Console.WriteLine(line.Text); } } Console.WriteLine(); }
注意事项
- 确保项目已安装
Newtonsoft.JsonNuGet包(你的代码中已引用using Newtonsoft.Json;,若未安装可通过NuGet控制台执行Install-Package Newtonsoft.Json)。 - 若SDK模型类后续有版本更新,需保证序列化/反序列化时的JSON结构与当前版本模型类一致,避免兼容性问题。
内容的提问来源于stack exchange,提问作者Karmegam S
相关产品推荐
相关产品推荐

