我正在使用另一个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());