如何将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

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

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