I am currently reading a json file from s3 location using the below code and then printing the data.
Json File
[
{
"name": "A",
"lastName" : "B"
},
{
"name": "C",
"lastName" : "D"
}
]
Reading data from s3
AwsBasicCredentials awsSourceBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey);
URI sourceUrl = new URI(ep);
S3Client s3Client= S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(awsSourceBasicCredentials))
.region(Region.AWS_GLOBAL)
.endpointOverride(sourceUrl)
.build();
ResponseInputStream object = s3Client.getObject(request -> request
.bucket(bucketName)
.key(key));
This ResponseInputStram I am priniting.
Say suppose I have a Name Object. Name.class
class Name
{
String name;
String lastName;
}
Is there a way that instead of printing I can create a List<Name>
?
So if you just want to read the JSON file and bind that into a Java object you can use Jackson for that:
try( var res = s3Client.getObject(request -> request
.bucket(bucketName)
.key(key)) ) {
Reader reader = new InputStreamReader( res, res.response().contentType() );
List<Name> names = objectMapper.readValue(reader, new TypeReference<List<Name>>(){});
}
And remember to add the dependency to your build environment:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.18.3</version>
</dependency>
Or
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
implementation("com.fasterxml.jackson.core:jackson-core:2.18.3")