JSON数据解析(5)

之前我们都是解析XML文件,虽然规范化了文件传输的定义格式,但是大家有没有意识到每次传输前都要进行元素声明,这样传输中将传出很多无用数据,导致传输数据量增大,而且解析xml操作很复杂,作者在之前编程中也几近崩溃,现在我们介绍一种轻量级的数据交换格式--JSON

JSON将对象中数据转化为字符串。在应用程序中传递,最重要的是在异步系统中进行服务器和客户端之间的数据传递,这里将在网络连接课程讲到,利用JSON解析打包发送手机端数据给服务器。

{
 "code":"状态码",
   "message":"返回信息/错误信息",
   "result":{
            "user_id":"用户ID"
   }
}

JSON结构是由外向内读

有点想数据库结构,先从spj读起,再访问子类

一个外部JSONObject保存多个字符串信息例如name,address,telephone和一个JSONArray对象

一个JSONArray对象保存多个JSONObject对象

每一个保存在JSONArray下的JSONObject保存多种数据类型。

现在将数据写入文档

Activity文件

public class MainActivity extends Activity {
	private String nameData[] = new String[] { "张依依", "蓝杰培训", "lanjie" };
	private int ageData[] = new int[] { 30, 5, 7 };
	private boolean isMarraiedData[] = new boolean[] { false, true, false };
	private double salaryData[] = new double[] { 3000.0, 5000.0, 9000.0 };
	private Date birthdayData[] = new Date[] { new Date(), new Date(),
			new Date() };
	private String companyName = "湖南大学(信息科学与工程学院)" ;
	private String companyAddr = "长沙市岳麓区麓山南路453" ;
	private String companyTel = "13283928931" ;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		JSONObject allData = new JSONObject(); // 建立最外面的节点对象
		JSONArray sing = new JSONArray(); // 定义数组
		for (int x = 0; x < this.nameData.length; x++) { // 将数组内容配置到相应的节点
			JSONObject temp = new JSONObject(); // 每一个包装的数据都是JSONObject
			try {
				temp.put("name", this.nameData[x]);//一个键对应相应数值
				temp.put("age", this.ageData[x]);
				temp.put("married", this.isMarraiedData[x]);
				temp.put("salary", this.salaryData[x]);
				temp.put("birthday", this.birthdayData[x]);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			sing.put(temp); // 保存多个JSONObject
		}
		try {
			allData.put("persondata", sing);
			allData.put("company", this.companyName) ; 
			allData.put("address", this.companyAddr) ;
			allData.put("telephone", this.companyTel) ;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { // 不存在不操作
			return; // 返回到程序的被调用处
		}
		File file = new File(Environment.getExternalStorageDirectory()
				+ File.separator + "eedata" + File.separator + "json.txt"); // 要输出文件的路径
		if (!file.getParentFile().exists()) { // 文件不存在
			file.getParentFile().mkdirs(); // 创建文件夹
		}
		PrintStream out = null;
		try {
			out = new PrintStream(new FileOutputStream(file));
			out.print(allData.toString()); // 将数据变为字符串后保存
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close(); // 关闭输出
			}
		}
	}
}

 然后在相应路径找到文件json.txt显示如下:


JSON数据解析(5)

接下来我们要试着把json文件解析出来

首先布局文件定义:

<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" 
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView 
		android:id="@+id/msg"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"/>
</LinearLayout>

 Activity  JSON解析

public class MainActivity extends Activity {
	private TextView msg = null ;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.msg = (TextView) super.findViewById(R.id.msg) ;
		String str = "[{\"id\":1,\"name\":\"张依依\",\"age\":21},"
				+ "{\"id\":2,\"name\":\"lanjie\",\"age\":10}]";
		StringBuffer buf = new StringBuffer() ;
		try {
			List<Map<String,Object>> all = this.parseJson(str) ;//json解析文本格式
			Iterator<Map<String,Object>> iter = all.iterator() ;
			while(iter.hasNext()){
				Map<String,Object> map = iter.next() ;
				buf.append("ID:" + map.get("id") + ",姓名:" + map.get("name")
						+ ",年龄:" + map.get("age") + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.msg.setText(buf) ;
	}

	private List<Map<String, Object>> parseJson(String data) throws Exception {
		List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
		JSONArray jsonArr = new JSONArray(data); // 是数组
		for (int x = 0; x < jsonArr.length(); x++) {
			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject jsonObj = jsonArr.getJSONObject(x);
			map.put("id", jsonObj.getInt("id"));
			map.put("name", jsonObj.getString("name"));
			map.put("age", jsonObj.getInt("age"));
			all.add(map);
		}
		return all;
	}
}

 实现效果如图:

 
JSON数据解析(5)
 

相关推荐