mengmeng
mengmeng

Reputation: 1506

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);

Upvotes: 4

Views: 6835

Answers (3)

Suzana
Suzana

Reputation: 4420

It's much easier with version 2 of the AWS Java SDK.

If you have converted the object to a JSON String, using GSON or Jackson, you can upload it via:

PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucket).key(s3Key).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString(jsonString));

No need to set the content length manually.

Upvotes: 0

Somuchandra
Somuchandra

Reputation: 11

public class JSONStringToFile {

public static void main(String[] args) throws IOException {

    JSONObject obj = new JSONObject();
    obj.put("Name", "somanna");
    obj.put("city", "bangalore");

    JSONArray company = new JSONArray();
    company.add("Compnay: mps");
    company.add("Compnay: paypal");
    company.add("Compnay: google");
    obj.put("Company List", company);

    // try-with-resources statement based on post comment below :)
    try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
        file.write(obj.toJSONString());
        System.out.println("Successfully Copied JSON Object to File...");
        System.out.println("\nJSON Object: " + obj);
    }
}

}

Upvotes: 0

SteffenJacobs
SteffenJacobs

Reputation: 412

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

Upvotes: 3

Related Questions