1.将数据写入json
原理是将业务数据对象写入json文件.这里的业务对象为User。
public void write2Json(String label,User user, String filePath) throw IOException{
File dir = getDirPath(filePath);
int num=0;
File file = new File(dir, label + ".json");
while(file.exists()){
num +=1;
file = new File(dir, label + "_" + num + ".json");
}
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.writeValue(file, user);
}
public File getDirPath(String path){
File dir = new File(path);
if (!dir.exists()){
if (!dir.mkdirs()){
logger.error("mkdir failed.");
}
}
}
2.读取json
读取json文件是将json文件恢复为业务对象,这里业务对象是User。
public User load(String path) throw IOException{
ObjectMapper mapper = new ObjectMapper();
File file = new File(path);
return mapper.readValue(file, User.class);
}