Google视觉标签未返回原始JSON Java

问题描述 投票:0回答:1

我正在尝试使响应采用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());

        }
    }
}

这是将打印与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
  }
}
java json google-vision
1个回答
0
投票

BatchAnnotateImagesResponse类扩展了com.google.api.client.json.GenericJson,但默认情况下不会生成JSON。您需要设置JsonFactory。您可以选择提供者:JacksonFactoryGsonFactory或其他。之后,toString方法应生成有效的JSON。示例:

© www.soinside.com 2019 - 2024. All rights reserved.