JAVA 格式化JSON数据并保存到json文件中的实例
使用fastjson格式化json数据并保存到文件
/**
*将JSON数据格式化并保存到文件中
*@paramjsonData需要输出的json数
*@paramfilePath输出的文件地址
*@return
*/
publicstaticbooleancreateJsonFile(ObjectjsonData,StringfilePath){
Stringcontent=JSON.toJSONString(jsonData,SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
//标记文件生成是否成功
booleanflag=true;
//生成json格式文件
try{
//保证创建一个新文件
Filefile=newFile(filePath);
if(!file.getParentFile().exists()){//如果父目录不存在,创建父目录
file.getParentFile().mkdirs();
}
if(file.exists()){//如果已存在,删除旧文件
file.delete();
}
file.createNewFile();
//将格式化后的字符串写入文件
Writerwrite=newOutputStreamWriter(newFileOutputStream(file),"UTF-8");
write.write(content);
write.flush();
write.close();
}catch(Exceptione){
flag=false;
e.printStackTrace();
}
returnflag;
}
补充知识:将json格式的数据保存到本地
1.创建jsonobject对象
JSONObjectjsonObject=newJSONObject();
2.以键值的形式存储数据
jsonObject.put(key,value);
3.将json格式的数据转化成字符串
jsonObject.toString
4.往本地写数据
//文件路径
Stringpath=Environment.getExternalStorageDirectory().toString()
+"/test.txt";
//判断文件是否存在
Filefile=newFile(path);
if(file.exists()){
Log.i("myTag","文件存在");
}else{
try{
file.createNewFile();
}catch(IOExceptione){
e.printStackTrace();
}
Log.i("myTag","文件创建成功");
}
try{
FileOutputStreamfileOutputStream=newFileOutputStream(file);
fileOutputStream.write(jsonString.getBytes());
//fileOutputStream.write(sbString.getBytes());
fileOutputStream.close();
Log.i("myTag","json数据保存到成功!!!");
}catch(Exceptione){
e.printStackTrace();
}
以上这篇JAVA格式化JSON数据并保存到json文件中的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下