如何将JSON响应字符串读取到Document AI的Document对象中?

我正在使用另一个API,该API调用了Google的Document AI API。我试图将文件中的JSON字符串读取到一个Document对象中。应该如何操作呢?

我尝试了以下方法,但没有成功。

import com.google.cloud.documentai.v1.Document;import java.io.FileInputStream;Document document = Document.parseFrom(new FileInputStream("src/main/resources/responseFromAPICall.json"));System.out.println(document.getText());

我遇到了以下错误:

Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.    at com.google.protobuf.InvalidProtocolBufferException.invalidEndTag(InvalidProtocolBufferException.java:129)    at com.google.protobuf.CodedInputStream$StreamDecoder.checkLastTagWas(CodedInputStream.java:2124)    at com.google.protobuf.CodedInputStream$StreamDecoder.readGroup(CodedInputStream.java:2358)

回答:

今天我也遇到了这个问题。这个回答为我提供了一个解决方案的起点。

如果你的JSON文件是从对Document AI的调用中保存的,并且看起来像这样:

{  "document": {    ...    "text": "...",    ...  },  "humanReviewStatus": {...}}

你可以使用以下代码片段:

import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import com.google.cloud.documentai.v1.Document;import com.google.cloud.documentai.v1.ProcessResponse;import com.google.protobuf.util.JsonFormat;Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");ProcessResponse.Builder responseBuilder = ProcessResponse.newBuilder();JsonFormat.parser().merge(Files.newBufferedReader(filePath), responseBuilder);Document document = responseBuilder.getDocument();System.out.println(document.getText());

如果你的JSON文件只包含”document”对象:

{  ...  "text": "...",  ...}

以下代码将能解决问题:

import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import com.google.cloud.documentai.v1.Document;import com.google.protobuf.util.JsonFormat;Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");Document.Builder docBuilder = Document.newBuilder();JsonFormat.parser().merge(Files.newBufferedReader(filePath), docBuilder);System.out.println(docBuilder.getText());

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注