您的位置:首页 > Web前端 > JavaScript

增删改查本地JSON

2015-06-26 16:43 567 查看

存储数据到JSON文件:

User u = new User();MessageUtil.cache=”D:\\WSE\\Weixin\\”String path = MessageUtil.cache + "WebContent\\config\\user.json";JSONObject jo = JSONObject.fromObject(u);FileWriter writer = new FileWriter(path, true);writer.write(jo.toString() + ",\r\n");writer.close();存储时为续写模式,而非替换。

读取本地JSON文件:

String path = MessageUtil.cache + "WebContent\\config\\user.json";String sets = ReadFile(path);JSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象for (int i = 0; i < ja.size(); i++) {User u = new User();jo.get("KEY").toString();//KEY为User存储时保存的属性。Return u}

ReadFile.java:

public static String ReadFile(String path) {String laststr = "";File file = new File(path);BufferedReader reader = null;try {reader = new BufferedReader(new FileReader(file));String tempString = null;int line = 1;// 一次读入一行,直到读入null为文件结束while ((tempString = reader.readLine()) != null) {// 显示行号//System.out.println("line " + line + ": " + tempString);laststr = laststr + tempString;line++;}reader.close();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}return laststr;}

更新本地JSON:

根据条件找到匹配对象,设置更新属性,然后移除源对象,添加新对象,最后在转为JSONARRAY
String path = MessageUtil.cache + "WebContent\\config\\user.json";String sets = ReadFile(path);// 读取本地jsonJSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象JSONObject newjo = null;for (int i = 0; i < ja.size(); i++) {JSONObject jo = ja.getJSONObject(i);if (jo.get("key").equals(key)) {//匹配条件User u = (User) JSONObject.toBean(jo, User.class);u.setToken(token);//需要更新的属性u.setPassword(password); //需要更新的属性newjo = JSONObject.fromObject(u);//转为JSON对象ja.remove(i);// 如果token无效,则删除该记录,i=i-1;}}ja.add(newjo);FileWriter fw = new FileWriter(path);fw.write("");// json文件fw.close();FileWriter writer = new FileWriter(path, true);// 重新写入jsonfor (int i = 0; i < ja.size(); i++) {writer.write(ja.get(i).toString() + ",\r\n");}writer.close();

删除本地JSON数据:

先转为JSONARRAY,进行移除,然后重新写入
String path = MessageUtil.cache + "WebContent\\config\\user.json";String sets = ReadFile(path);// 读取本地jsonJSONArray ja = JSONArray.fromObject("[" + sets + "]");// 格式化成json对象JSONObject newjo = null;for (int i = 0; i < ja.size(); i++) {JSONObject jo = ja.getJSONObject(i);if (jo.get("key").equals(key)) {ja.remove(i);// 如果token无效,则删除该记录,}}FileWriter fw;try {FileWriter writer = new FileWriter(path, true);// 重新写入jsonfw = new FileWriter(path);fw.write("");// json文件fw.close();for (int i = 0; i < ja.size(); i++) {writer.write(ja.get(i).toString() + ",\r\n");}writer.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: