Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON String to File in Java

I'm trying to convert an Object to JSON then convert it to File to be able to send it to AWS S3.

Is there a way to convert the String in the most efficient way? Thank you!

Here is my code:

String messageBody = new Gson().toJson(thisIsADtoObject);

And for the S3

PutObjectRequest request = new PutObjectRequest(s3BucketName, key, file);
        amazonS3.putObject(request);
like image 807
mengmeng Avatar asked Oct 20 '25 09:10

mengmeng


1 Answers

As far as I know, to create a file object to send to AWS, you will have to create the actual file on disk, e.g. with a PrintStream:

File file = new File("path/to/your/file.name");
try (PrintStream out = new PrintStream(new FileOutputStream(file))) {
    out.print(messageBody);
} 

Instead of using the constructor taking a file, you might want to use the one which takes an InputStream:

PutObjectRequest request = new PutObjectRequest(s3BucketName, key, inputStream, metadata);
        amazonS3.putObject(request);

To convert a String to an InputStream, use

new ByteArrayInputStream(messageBody.getBytes(StandardCharsets.UTF_8));

Link to SDK JavaDoc

like image 52
SteffenJacobs Avatar answered Oct 21 '25 21:10

SteffenJacobs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!