【问题标题】:Convert JSON String to File in Java在 Java 中将 JSON 字符串转换为文件
【发布时间】:2020-04-26 20:26:55
【问题描述】:

我正在尝试将Object 转换为JSON,然后将其转换为File 以便能够将其发送到 AWS S3。

有没有办法以最有效的方式转换字符串? 谢谢!

这是我的代码:

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

对于 S3

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

【问题讨论】:

  • 这里发布的代码非常不清楚。请通过发布一些您尝试过的更好的代码 sn-p 来详细说明。

标签: java json spring amazon-s3


【解决方案1】:

据我所知,要创建要发送到 AWS 的文件对象,您必须在磁盘上创建实际文件,例如带有PrintStream:

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

而不是使用构造函数获取文件,您可能希望使用获取InputStream 的构造函数:

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

要将字符串转换为InputStream,请使用

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

Link to SDK JavaDoc

【讨论】:

  • 为此感谢!现在我收到错误`没有为流数据指定内容长度。流内容将在内存中缓冲,并可能导致内存不足错误。` 创建 inputStream 和元数据时
  • 我想你需要在元数据对象中指定流的内容长度
【解决方案2】:

公共类 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);
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 2012-07-19
    • 2023-04-01
    • 2016-08-28
    • 2016-06-25
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    相关资源
    最近更新 更多