我试图让响应采用格式,出于某种原因,谷歌的示例代码在响应中JSON抛出了一堆。{}使用下面的代码,我可以获得响应,但不是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());
}
}
}
以下是示例代码将打印的接近 JSON 但格式错误的内容。反正有没有让它正确格式化?
responses {
label_annotations {
mid: "/m/02l215"
description: "Reflection"
score: 0.9883928
topicality: 0.9883928
}
label_annotations {
mid: "/m/05h0n"
description: "Nature"
score: 0.98085856
topicality: 0.98085856
}
label_annotations {
mid: "/m/03d28y3"
description: "Natural landscape"
score: 0.9740803
topicality: 0.9740803
}
label_annotations {
mid: "/m/0838f"
description: "Water"
score: 0.9714835
topicality: 0.9714835
}
label_annotations {
mid: "/m/038hg"
description: "Green"
score: 0.9620494
topicality: 0.9620494
}
label_annotations {
mid: "/m/01bqvp"
description: "Sky"
score: 0.96003544
topicality: 0.96003544
}
label_annotations {
mid: "/m/015s2f"
description: "Water resources"
score: 0.9593428
topicality: 0.9593428
}
label_annotations {
mid: "/m/07j7r"
description: "Tree"
score: 0.9462387
topicality: 0.9462387
}
label_annotations {
mid: "/m/01fnns"
description: "Vegetation"
score: 0.9326158
topicality: 0.9326158
}
label_annotations {
mid: "/m/02yq2x"
description: "Reflecting pool"
score: 0.8776601
topicality: 0.8776601
}
}
编辑:我想对我的帖子进行快速编辑,因为虽然这里的所有答案都很棒并且帮助我发现这是让它按我想要的方式工作的原因。
String theData = com.google.protobuf.util.JsonFormat.printer().print(response);