如何使用S3AsyncClient从S3读取JSON文件

5
我不知道如何将S3中的JSON文件读入内存作为String。我找到的示例调用getObjectContent(),但是在我从S3AsyncClient获取的GetObjectResponse中没有此选项。我正在尝试的代码是来自AWS的示例代码。
// Creates a default async client with credentials and AWS Region loaded from the
// environment
S3AsyncClient client = S3AsyncClient.create();

// Start the call to Amazon S3, not blocking to wait for the result
CompletableFuture<GetObjectResponse> responseFuture =
        client.getObject(GetObjectRequest.builder()
                                         .bucket("my-bucket")
                                         .key("my-object-key")
                                         .build(),
                         AsyncResponseTransformer.toFile(Paths.get("my-file.out")));

// When future is complete (either successfully or in error), handle the response
CompletableFuture<GetObjectResponse> operationCompleteFuture =
        responseFuture.whenComplete((getObjectResponse, exception) -> {
            if (getObjectResponse != null) {
                // At this point, the file my-file.out has been created with the data
                // from S3; let's just print the object version
                System.out.println(getObjectResponse.versionId());
            } else {
                // Handle the error
                exception.printStackTrace();
            }
        });

// We could do other work while waiting for the AWS call to complete in
// the background, but we'll just wait for "whenComplete" to finish instead
operationCompleteFuture.join();

这段代码该如何修改,才能从GetObjectResponse中获得真实的JSON内容?
2个回答

12

响应转换为字节后,可以将其转换为字符串:

S3AsyncClient client = S3AsyncClient.create();

GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket("my-bucket").key("my-object-key").build();

client.getObject(getObjectRequest, AsyncResponseTransformer.toBytes())
      .thenApply(ResponseBytes::asUtf8String)
      .whenComplete((stringContent, exception) -> {
          if (stringContent != null)
              System.out.println(stringContent);
          else
              exception.printStackTrace();
      });

1
你可以使用AsyncResponseTransformer.toBytes将响应保存为字节数组而不是文件。 javadoc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接