標籤:android json
廢話不多說,直接上代碼,布局檔案:
<?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:orientation="vertical" > <TextView android:id="@+id/mytext" android:layout_width="fill_parent" android:layout_height="wrap_content" /></LinearLayout>
.java:
package org.lxh.demo;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.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class Hello extends Activity {private TextView textView;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); // 生命週期方法super.setContentView(R.layout.main); // 設定要使用的布局管理器this.textView = (TextView) findViewById(R.id.mytext);String str = "{\"memberdata\":[{\"id\":1,\"name\":\"yayun\",\"age\":25},"+ "{\"id\":2,\"name\":\"qiangge\",\"age\":26}],\"company\":\"NJUPT\"}";StringBuffer buffer = new StringBuffer();Map<String, Object> resultMap = this.parseJson(str);buffer.append("單位名稱:" + resultMap.get("company") + "\n");@SuppressWarnings("unchecked")List<Map<String, Object>> all = (List<Map<String, Object>>) resultMap.get("memberdata");// 強制轉換Iterator<Map<String, Object>> iter = all.iterator();while (iter.hasNext()) {Map<String, Object> map = iter.next();buffer.append("ID:" + map.get("id") + "姓名:" + map.get("name")+ "\n");}this.textView.setText(buffer);}private Map<String, Object> parseJson(String data) {Map<String, Object> allMap = new HashMap<String, Object>();try {JSONObject allDataJsonObject = new JSONObject(data);allMap.put("company", allDataJsonObject.getString("company"));JSONArray array = allDataJsonObject.getJSONArray("memberdata");List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();for (int i = 0; i < array.length(); i++) {Map<String, Object> map = new HashMap<String, Object>();JSONObject jsonObject = array.getJSONObject(i);map.put("id", jsonObject.getInt("id"));map.put("name", jsonObject.getString("name"));map.put("age", jsonObject.getInt("age"));all.add(map);}allMap.put("memberdata", all);// 將List<Map<String,// Object>>裝入Map<String, Object>} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return allMap;}}
運行執行個體效果如下:
我的應用程式: http://openbox.mobilem.360.cn/index/d/sid/2966005
http://android.myapp.com/myapp/detail.htm?apkName=com.yayun.gitlearning
喜歡的朋友可以關注我,多交流,謝謝。
Android實戰--解析稍複雜JSON資料DEMO