You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:31:23