[英]Writing JSON Object as Object not as String to File
我想將JSON對象寫入文件。當前我嘗試使用ObjectMapper和Gson,但他們將JSON編寫為JSONString,因此輸出文件具有JSON字符串而不是對象。 那么有沒有一種方法可以將JSON對象寫為Object而不是String
JSONObject responseData = new JSONObject(response.getBody().toString());
org.json.simple.JSONObject object = new
org.json.simple.JSONObject(responseData.toMap());
ObjectMapper objMapper = new ObjectMapper();
objMapper.writeValue(new File(path) , object);
現在,上面的代碼將JSON對象作為String寫入文件而不是JSONObject。
不要使用ObjectMapper。 您可以使用org.json.simple。*包本身來實現。
package com.tutorial
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class JosnObjectWrite {
public static void main(String[] args) throws IOException {
JSONObject responseData = new JSONObject(response.getBody().toString());
JSONObject object = new JSONObject(responseData.toMap());
try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
file.write(object.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + object);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.