Android read write json

来源:互联网 发布:云计算 校园招聘 编辑:程序博客网 时间:2024/06/01 21:12

直接贴代码了,这个是用google提供的json库 gson 2.5 下载地址download

private void loadData(){File fileDir = getFilesDir();String fileDirString = fileDir.getPath();String jsonFilePath = fileDirString + File.separator + FILE_NAME_JSON;File jsonFile = new File(jsonFilePath);if (jsonFile.exists() == false) {try {boolean bret = jsonFile.createNewFile();if (false == bret) {return;}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return;}}writeData(jsonFilePath);readData(jsonFilePath);}private void writeData(final String jsonFilePath){JSONObject jsonObject = new JSONObject();try {jsonObject.put("id", "1222");jsonObject.put("name", "Mrs Joden.");jsonObject.put("phone", "224-33223624");} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();return;}FileWriter fileWriter = null;try {fileWriter = new FileWriter(jsonFilePath);fileWriter.write(jsonObject.toString());fileWriter.flush();} catch (Exception e) {// TODO: handle exception}finally{if (null != fileWriter) {try {fileWriter.close();fileWriter = null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}private void readData(final String jsonFilePath){InputStream inputStream = null;String jsonString;try {inputStream = new FileInputStream(jsonFilePath);int size = inputStream.available();byte buffer[] = new byte[size];inputStream.read(buffer);jsonString = new String(buffer,"UTF-8");} catch (Exception e) {// TODO: handle exceptionreturn;}finally{if (null != inputStream) {try {inputStream.close();inputStream = null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}String s = jsonString;}


0 0
原创粉丝点击