Android学习第七天————将数据保存为JSON格式,通过JSONObject和JSONReader来解析JSON数据

来源:互联网 发布:张正隆雪白血红知乎 编辑:程序博客网 时间:2024/05/22 02:15

一、将数据保存为JSON格式

//将数据用JSON写入文本public void jsonwrite() {// 创建一组姓名数据String[] nameArr = new String[] { "小李", "萧晨", "小张", "小王" };// 创建一组年龄数据int[] ageArr = new int[] { 23, 24, 22, 25 };// 最外层json对象JSONObject jsonObject = new JSONObject();// json数组对象JSONArray jsonArray = new JSONArray();// 内层json对象JSONObject innerJsonObject = null;for (int i = 0; i < nameArr.length; i++) {innerJsonObject = new JSONObject();//实例化内层对象try {innerJsonObject.put("姓名", nameArr[i]);innerJsonObject.put("年龄", ageArr[i]);jsonArray.put(innerJsonObject);//将内层对象放进jsonArray中} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {jsonObject.put("info", jsonArray);//将数组对象放进Json对象中} catch (JSONException e) {e.printStackTrace();}File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "sd" + File.separator + "json.txt");//设置JSON文件存储路径try {PrintStream printStream = new PrintStream(new FileOutputStream(file));printStream.print(jsonObject);//将JSON存储到文件} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
二、用JSONObject来解析JSON文件

//解析JSON文件public void jsonParse(){File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "sd" + File.separator + "json.txt");//解析的XML文件try {String jsonInfo="";Scanner scanner=new Scanner(new FileInputStream(file));//读取输入流while(scanner.hasNext()){jsonInfo+=scanner.next();}try {JSONObject jsonObject=new JSONObject(jsonInfo);//创建JSON对象JSONArray jsonArray=jsonObject.getJSONArray("info");//获得名称为info的对象//System.out.println(jsonArray.length());for(int i=0;i<jsonArray.length();i++){//遍历数组对象中所有的对象元素String name=jsonArray.getJSONObject(i).getString("姓名");int age=jsonArray.getJSONObject(i).getInt("年龄");System.out.println(name+","+age);}} catch (JSONException e) {e.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
三、通过JSONReader来解析JSON文件

//解析JSON通过JSONReaderpublic void jsonReader(){File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "sd" + File.separator + "json.txt");//获取解析文件的路径try {JsonReader jsonReader=new JsonReader(new InputStreamReader(new FileInputStream(file)));//获得JSONReader的对象jsonReader.beginObject();//打开json读取对象while(jsonReader.hasNext()){String name=jsonReader.nextName();//获得对象名称if(name.equals("info")){jsonReader.beginArray();//打开json读取数组while(jsonReader.hasNext()){jsonReader.beginObject();//打开json读取对象while(jsonReader.hasNext()){String obName=jsonReader.nextName();if(obName.equals("姓名2")){System.out.println(jsonReader.nextString());}else if(obName.equals("年龄")){System.out.println(jsonReader.nextInt());}else if(obName.equals("姓名")){System.out.println(jsonReader.nextString());}}jsonReader.endObject();}jsonReader.endArray();}}jsonReader.endObject();} catch (Exception e) {e.printStackTrace();}}




0 0