把对像生成json并存储到文件

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() {
        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("创建文件失败{}", ConfPath.toAbsolutePath(), e);
        }

        try {
            Files.write(ConfPath, jsonString.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
        } catch (Exception ex) {
            logger.error("写入配置文件失败{}", ConfPath.toAbsolutePath(), ex);
        }
    }

猜你喜欢

转载自www.cnblogs.com/liuxm2017/p/10168024.html