Java Google vision响应标签未以原始JSON格式返回
我试图让响应采用Java Google vision响应标签未以原始JSON格式返回,java,json,google-cloud-vision,google-vision,json-serialization,Java,Json,Google Cloud Vision,Google Vision,Json Serialization,我试图让响应采用JSON格式,出于某种原因,Google的示例代码在响应中抛出了一堆{}。使用下面的代码,我可以得到响应,但不是JSON格式 public static void main(String... args) throws Exception { // Instantiates a client try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
JSON
格式,出于某种原因,Google的示例代码在响应中抛出了一堆{}
。使用下面的代码,我可以得到响应,但不是JSON
格式
public static void main(String... args) throws Exception {
// Instantiates a client
try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
// The path to the image file to annotate
String fileName = "src/main/resources/city-park.jpg";
// Reads the image file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString imgBytes = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.build();
requests.add(request);
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
System.out.println(response.toString());
}
}
}
编辑:我想对我的帖子进行一次快速编辑,因为这里的所有答案都很好,我发现这正是我想要的工作方式。String theData=com.google.protobuf.util.JsonFormat.printer().print(响应)
类扩展了com.google.api.client.json.GenericJson
,但默认情况下它不会生成json
。你需要设置。您可以选择提供程序:,或其他。之后,toString
方法应该生成有效的JSON
。例如:
response.setFactory(JacksonFactory.getDefaultInstance());
response.toString();
另见:
response.setFactory(JacksonFactory.getDefaultInstance());
response.toString();