把对像生成json并存储到文件
生活随笔
收集整理的這篇文章主要介紹了
把对像生成json并存储到文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.創(chuàng)建實體對像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() {return id;}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("創(chuàng)建文件失敗{}", ConfPath.toAbsolutePath(), e);}try {Files.write(ConfPath, jsonString.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);} catch (Exception ex) {logger.error("寫入配置文件失敗{}", ConfPath.toAbsolutePath(), ex);}}
?
轉(zhuǎn)載于:https://www.cnblogs.com/liuxm2017/p/10168024.html
總結(jié)
以上是生活随笔為你收集整理的把对像生成json并存储到文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高堂指的是什么人?
- 下一篇: 负二项分布学习[转载]