0

解析 Google Vision API 响应时出现 ClassCastException

要求

visionApiRequest {"requests":[{"features":[{"maxResults":2,"type":"LOGO_DETECTION"}],"image":{"source":{"imageUri":"https://www.tenfold.com/wp-content/uploads/2017/05/icon-sap-hybris.png"}}}]}

回复

visionApiResponse {  "responses": [    {      "logoAnnotations": [        {          "mid": "/m/0gwz218",          "description": "Hybris",          "score": 0.17361198,          "boundingPoly": {            "vertices": [              {                "x": 65,                "y": 58              },              {                "x": 114,                "y": 58              },              {                "x": 114,                "y": 120              },              {                "x": 65,                "y": 120              }            ]          }        }      ]    }  ]}

解析代码片段:

String resp = "";
    while (httpResponseScanner.hasNext()) {
        final String line = httpResponseScanner.nextLine();
        resp += line;
        //System.out.println(line); // alternatively, print the line of response
    }
    System.out.println("visionApiResponse "+resp);


    BatchAnnotateImagesResponse annotateImagesResponse = new ObjectMapper().readValue(resp, BatchAnnotateImagesResponse.class);

    List<AnnotateImageResponse> responses = annotateImagesResponse.getResponses();

    for (AnnotateImageResponse res : responses) {

        System.out.println(res);
    }

行异常:for(AnnotateImageResponse res:responses){

线程“主”java.lang.ClassCastException 中的异常:java.util.LinkedHashMap 无法转换为 com.google.api.services.vision.v1.model.AnnotateImageResponse

依赖:google-api-services-vision-v1-rev370-1.23.0.jar

如何处理?

4

1 回答 1

0

使用com.fasterxml.jackson.core.type.TypeReference解决

List<AnnotateImageResponse> responses = mapper.convertValue(annotateImagesResponse.getResponses(), new TypeReference<List<AnnotateImageResponse>>() {
    });
于 2018-02-09T13:24:59.477 回答