所以在将二维数组json_encode之后,需要再使用addslashes()处理一下,再存入数据库。
需呀使用的时候,提取出来,先用stripslashes()处理一下,再json_decode()就能提取出原始数组了java解析json格式文件,再保存在数据库的方法:
1:定义一个实体类
2:用json lib将json字符串转为Java对象
3:用jdbc或hibernate将java对象存入数据库
直接读写文件,再把读出来的文件内容格式化成json,再用JDBC、Mybatis或者其他框架将json数据存入数据库。
假设实体类是这样的:
public class ElectSet {public String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
public String getXueqi() {
return xueqi;
}
public void setXueqi(String xueqi) {
thisxueqi = xueqi;
}
public String getXuenian() {
return xuenian;
}
public void setXuenian(String xuenian) {
thisxuenian = xuenian;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
thisstartTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
thisendTime = endTime;
}
public int getMenshu() {
return menshu;
}
public void setMenshu(int menshu) {
thismenshu = menshu;
}
public String getIsReadDB() {
return isReadDB;
}
public void setIsReadDB(String isReadDB) {
thisisReadDB = isReadDB;
}
}
有一个json格式的文件,存的信息如下:
Setsjson:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}
具体 *** 作:
/
取出文件内容,填充对象
/
public ElectSet findElectSet(String path){
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//获得json文件的内容
JSONObject jo=JSONObjectfromObject(sets);//格式化成json对象
//Systemoutprintln("------------" jo);
//String name = jogetString("xuenian");
//Systemoutprintln(name);
electsetsetXueqi(jogetString("xueqi"));
electsetsetXuenian(jogetString("xuenian"));
electsetsetStartTime(jogetString("startTime"));
electsetsetEndTime(jogetString("endTime"));
electsetsetMenshu(jogetInt("menshu"));
electsetsetIsReadDB(jogetString("isReadDB"));
return electset;
}
//设置属性,并保存
public boolean setElect(String path,String sets){
try {
writeFile(path,sets);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
return false;
}
}
//读文件,返回字符串
public String ReadFile(String path){
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try {
//Systemoutprintln("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = readerreadLine()) != null) {
//显示行号
Systemoutprintln("line " line ": " tempString);
laststr = laststr tempString;
line ;
}
readerclose();
} catch (IOException e) {
eprintStackTrace();
} finally {
if (reader != null) {
try {
readerclose();
} catch (IOException e1) {
}
}
}
return laststr;
}
将获取到的字符串,入库即可。
/将List转化为json字符串
@paramlistList
@returnStringjson格式的字符串
/
publicstatic <T> String getString4List(List<T> list)
{
JSONArray jsonArray = JSONArrayfromObject(list);
return jsonArraytoString();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)