JOSN数据解析
对于XML,虽然它规范化了数据的格式,但是由于每一个要传递的数值都需要使用元素进行声明,所以在传输数据时往往得传递许多没用的数据,从而导致要传输的数据量增大。而且XML解析的操作也比较复杂,所以现在经常会用到另一种轻量级的交换格式——JSON(JavaScript Object Notation)。JSON用纯文本格式来存储数据,它可以将对象所表示的数据转换成字符串,然后在各个应用程序之间传递这些字符串,或者在异步系统中进行服务器和客户端之间的数据传递。使用JSON时常用到的类:JSONObject和JSONArray。
例 1 输出JSON文件格式到文件
程序运行后得到的文件内容如下:
下面对JSON的数据保存格式进行具体说明:
{ //JSONObject数据都是使用{}包裹的 “blogRecord” //JSONObject按照key/value的形式保存,所以此处为保存的key : //key和value之间数据的分隔符 [ //个key下有多个value时,用[]包裹,即JSONArray { “theurl” //JSONArray中保存的JSONObject中的key : //key和value的分隔符 “www.csdn.net” //JSONArray中保存的JSONObject中的value }, {“theurl”:”www.lion.com”}, //一个JSONObject对象 {“theurl”:”blog.csdn.net/runninglion”} //一个JSONObject对象 ] }
实现过程:
1. 编写MainActivity程序,要保存的数据在程序中给出
package org.lion.jsontest; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.Environment; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.main); String data[] = { "www.csdn.net", "www.lion.com", //默认存储的信息 "blog.csdn.net/runninglion" }; JSONObject allData = new JSONObject(); JSONArray array = new JSONArray(); for (int k = 0; k < data.length; k++) { JSONObject temp = new JSONObject(); try { temp.put("blog", data[k]); //设置要保存的数据 } catch (JSONException e) { e.printStackTrace(); } array.put(temp); //保存一个信息 } try { allData.put("blogRecord", array); //保存所有的数据 } catch (JSONException e) { e.printStackTrace(); } if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { //如果sdcard不存在则返回调用处 return; } File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "running" + File.separator + "lionJson.txt"); if (!file.getParentFile().exists()) { //如果父文件夹不存在,则创建新文件夹 file.getParentFile().mkdirs(); } PrintStream out = null; try { //实例化打印流对象 out = new PrintStream(new FileOutputStream(file)); out.print(allData.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } }
2. 不要忘了在AndroidManifest.xml文件中添加授权申请
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
JSONArray和JSONObject之间的关系可以进行嵌套表示,JSON会根据这两个类的关系排列数据,下面来看一个稍微复杂一点的例子。
例 2 以下程序将要保存一个公司的基本信息(公司名称、地址、电话等)以及公司里的员工的相关信息(员工的姓名、性别、年龄、是否已婚、工资、出生年月等)。
程序运行后得到的数据如下:
实现过程:
1. 编写MainActivity程序,要保存的数据在程序中给出
package org.lion.jsontest; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.Environment; public class MainActivity extends Activity { private String names[] = new String[] { "running", "lion", "kelvin" }; private String sex[] = new String[] { "male", "male", "male" }; private boolean isMarraied[] = new boolean[] { false, false, true }; private int age[] = new int[] { 18, 18, 16 }; private double salary[] = new double[] { 9999, 8888, 9999 }; //private Date birthday[] = new Date[] { new Date(), new Date(), new Date() }; private String companyName = "狂人日记"; private String companyAddress = "天上人间9号楼"; private String companyTel = "5201314"; @Override public void onCreate(Bundle savedInstanceState) { JSONObject allData = new JSONObject(); //建立最外层的allData对象 JSONArray array = new JSONArray(); super.onCreate(savedInstanceState); super.setContentView(R.layout.main); for (int k = 0; k < names.length; k++) { JSONObject temp = new JSONObject(); try { //temp.put("birthday", birthday[k]); temp.put("name", names[k]); //设置要保存的数据 temp.put("sex", sex[k]); temp.put("age", age[k]); temp.put("salary", salary[k]); temp.put("married", isMarraied[k]); } catch (JSONException e) { e.printStackTrace(); } array.put(temp); //保存一组信息 } try { allData.put("employeesInfo", array); //保存上面的所有数据 allData.put("companyName", companyName); //保存数据 allData.put("companyAddress", companyAddress); allData.put("companyTelephone", companyTel); } catch (JSONException e) { e.printStackTrace(); } if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { //如果sdcard不存在,则返回被调用处 return; } File file = new File(Environment.getExternalStorageDirectory() .toString() + File.separator + "running" + File.separator + "employeesJson.txt"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } PrintStream out = null; try { out = new PrintStream(new FileOutputStream(file)); out.print(allData.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } }
例 3 下面的程序演示如何进行JSON数据解析的操作,程序将直接解析一个JSON的数组数据。JSON解析出的数据如下图
实现过程:
1. 编写main.xml布局管理器
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00ff00" android:orientation="vertical"> <TextView android:id="@+id/message" android:textColor="#0000ff" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
2. 编写MainActivity程序,解析数据
package org.lion.jsontest; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { private TextView message = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.main); message = (TextView)findViewById(R.id.message); String str = "{\"studata\":" + "[{\"id\":1,\"name\":\"kelvin\",\"age\":18}," + "{\"id\":2,\"name\":\"running\",\"age\":16}," + "{\"id\":3,\"name\":\"lion\",\"age\":18}]," + "\"class\":\"高三0610班\"}"; StringBuffer buff = new StringBuffer(); try{ Map<String, Object> result = parseJson(str); //JSON解析 buff.append("班级:" + result.get("class") + "\n"); @SuppressWarnings("unchecked") List<Map<String, Object>> allstu = (List<Map<String, Object>>)result.get("studata"); Iterator<Map<String, Object>> iter = allstu.iterator(); while(iter.hasNext()){ Map<String, Object> map = iter.next(); //取出每一个保存的数据 buff.append("ID:" + map.get("id") + ", 姓名:" + map.get("name") + ", 年龄:" + map.get("age") + "\n"); //保存内容 } }catch(Exception e){ e.printStackTrace(); } message.setText(buff); } public Map<String, Object> parseJson(String data) throws Exception{ Map<String, Object> allMap = new HashMap<String, Object>(); JSONObject allData= new JSONObject(data); allMap.put("class", allData.getString("class")); //取出并设置class JSONArray array = allData.getJSONArray("studata"); //取出JSONArray List<Map<String, Object>> all = new ArrayList<Map<String, Object>>(); for(int k=0; k<array.length(); k++){ //取出数组中的每一个JSONObject Map<String, Object> map = new HashMap<String, Object>(); JSONObject obj = array.getJSONObject(k); //取出每一个JSONObject map.put("id", obj.getInt("id")); //取出并保存ID内容 map.put("name", obj.getString("name")); map.put("age", obj.getInt("age")); all.add(map); //添加到集合中 } allMap.put("studata", all); //保存集合 return allMap; } }