您的位置:首頁技術文章
文章詳情頁

JAVA 格式化JSON數據并保存到json文件中的實例

瀏覽:2日期:2022-08-22 15:40:21

使用fastjson格式化json數據并保存到文件

/** * 將JSON數據格式化并保存到文件中 * @param jsonData 需要輸出的json數 * @param filePath 輸出的文件地址 * @return */ public static boolean createJsonFile(Object jsonData, String filePath) { String content = JSON.toJSONString(jsonData, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); // 標記文件生成是否成功 boolean flag = true; // 生成json格式文件 try { // 保證創建一個新文件 File file = new File(filePath); if (!file.getParentFile().exists()) { // 如果父目錄不存在,創建父目錄 file.getParentFile().mkdirs(); } if (file.exists()) { // 如果已存在,刪除舊文件 file.delete(); } file.createNewFile(); // 將格式化后的字符串寫入文件 Writer write = new OutputStreamWriter(new FileOutputStream(file), 'UTF-8'); write.write(content); write.flush(); write.close(); } catch (Exception e) { flag = false; e.printStackTrace(); } return flag; }

補充知識:將json格式的數據保存到本地

1.創建jsonobject對象

JSONObject jsonObject = new JSONObject();

2.以鍵值的形式存儲數據

jsonObject.put(key, value);

3.將json格式的數據轉化成字符串

jsonObject.toString

4.往本地寫數據

//文件路徑String path = Environment.getExternalStorageDirectory().toString() + '/test.txt';//判斷文件是否存在File file = new File(path); if (file.exists()) { Log.i('myTag', '文件存在'); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } Log.i('myTag', '文件創建成功'); } try { FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(jsonString.getBytes()); // fileOutputStream.write(sbString.getBytes()); fileOutputStream.close(); Log.i('myTag', 'json數據保存到成功!??!'); } catch (Exception e) { e.printStackTrace(); }

以上這篇JAVA 格式化JSON數據并保存到json文件中的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
国产综合久久一区二区三区