Go 谷歌云视觉API。戈朗。如何获取API JSON

Go 谷歌云视觉API。戈朗。如何获取API JSON,go,google-cloud-vision,Go,Google Cloud Vision,我将Google Cloud Vision API与Go SDK结合使用。 在某些情况下,我不想使用Golang结构来读取API结果,我只想获得API调用的完整JSON响应。比如说, // detectDocumentText gets the full document text from the Vision API for an // image at the given file path. func detectDocumentTextURI(w io.Writer, file str

我将Google Cloud Vision API与Go SDK结合使用。 在某些情况下,我不想使用Golang结构来读取API结果,我只想获得API调用的完整JSON响应。比如说,

// detectDocumentText gets the full document text from the Vision API for an
// image at the given file path.
func detectDocumentTextURI(w io.Writer, file string) error {
        ctx := context.Background()

        client, err := vision.NewImageAnnotatorClient(ctx)
        if err != nil {
                return err
        }

        image := vision.NewImageFromURI(file)
        annotation, err := client.DetectDocumentText(ctx, image, nil)
        if err != nil {
                return err
        }

        if annotation == nil {
                fmt.Fprintln(w, "No text found.")
        } else {
                fmt.Fprintf(w, "API Response %s", ...JSON...)
        }

        return nil
}

如何从注释结构中获取JSON?有可能吗?

JSON中是否有您特别想要的东西?如果您试图探索返回的内容,可以将响应对象打印为JSON:

json, err := json.MarshalIndent(annotation, "", "  ")
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(json))
从这个调用中获取原始JSON响应有点困难,因为它使用的是gRPC,而不是JSON。如果您遵循客户机代码一段时间(它是开源的),您最终会得到:


您可以看到该函数构建请求、发送请求并返回响应(与调用原始函数得到的原始响应相同,仅限于
res.FullTextAnnotation
)。请参阅。

谢谢。如果使用gRPC,则不可能获得JSON。我必须手动生成JSON。是的。我用一个片段更新了我的答案,为注释响应漂亮地打印JSON。
func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error)