把對像生成json並存儲到檔案
阿新 • • 發佈:2018-12-24
1.建立實體對像json
import com.alibaba.fastjson.annotation.JSONField; import java.util.Date; public class Student { private int id; private String name; @JSONField(format = "yyyy-MM-dd hh:mm:ss") private Date birthDay; private boolean sex; public int getId() { returnid; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) {this.birthDay = birthDay; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } }
2.使用fastjson生成 json字串並寫入檔案
import com.alibaba.fastjson.JSONObject; import entities.Student; import java.nio.charset.StandardCharsets;import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Date;
private Path getConfPath() { String appPath = System.getProperty("user.dir"); Path ConfPath = Paths.get(appPath, "app.conf"); return ConfPath; } private String read() { Path ConfPath = getConfPath(); if (!Files.exists(ConfPath)) { write(); } byte[] bytes = new byte[]{}; try { bytes = Files.readAllBytes(ConfPath); } catch (Exception e) { logger.error("讀取檔案失敗{}", ConfPath.toAbsolutePath(), e); } String jsonString = new String(bytes); return jsonString; } private void write() { Student stu = new Student(); stu.setId(1); stu.setSex(false); stu.setBirthDay(new Date()); stu.setName("jack"); String jsonString = JSONObject.toJSONString(stu,true); Path ConfPath = getConfPath(); try { if (!Files.exists(ConfPath)) Files.createFile(ConfPath); } catch (Exception e) { logger.error("建立檔案失敗{}", ConfPath.toAbsolutePath(), e); } try { Files.write(ConfPath, jsonString.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); } catch (Exception ex) { logger.error("寫入配置檔案失敗{}", ConfPath.toAbsolutePath(), ex); } }