Java+Retrofit调用Google Vision API TEXT_DETECTION时textAnnotations为空
问题原因及解决办法
问题根源
你的Java模型类和Google Vision API返回的textAnnotations结构完全不匹配,导致Retrofit(底层的JSON解析库,比如Gson)无法正确映射数据,最终得到空对象列表。
Google Vision API的textAnnotations响应结构是:
- 数组的第一个元素包含
locale、完整文本description和对应边界框 - 数组后续元素是单个字符/单词级别的文本片段,仅包含
description和边界框,无locale
而你定义的TextAnnotations类错误地将单个元素拆成了InTextAnnotationWithLocale和List<InTextAnnotation>两个子对象,这和实际返回的JSON结构完全不符,解析自然失败。
解决办法
直接修正模型类,让textAnnotations的元素结构和API返回一致:
//Root class //... class Response { @SerializedName("textAnnotations") List<TextAnnotation> textAnnotations; // 类名改为单数更贴合单个元素的语义 @SerializedName("fullTextAnnotation") FullTextAnnotation fullTextAnnotation; } // 修正后的单个文本注解类,完全匹配API返回的结构 class TextAnnotation { @SerializedName("locale") String locale; // 仅数组第一个元素会有该字段,其余元素为null @SerializedName("description") String description; @SerializedName("boundingPoly") BoundingPoly boundingPoly; } class BoundingPoly { @SerializedName("vertices") List<Vertex> vertices; } class Vertex { @SerializedName("x") int x; @SerializedName("y") int y; } //fullTextAnnotation //...
修改后,Retrofit就能正确解析textAnnotations数组中的每个对象,不会再出现空对象列表的情况。
内容的提问来源于stack exchange,提问作者StarCue
相关产品推荐
相关产品推荐

