废话不多说,直接上代码,布局文件:
<?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 block e.printStackTrace(); } return allMap; } }
运行实例效果如下:
我的应用: http://openbox.mobilem.360.cn/index/d/sid/2966005
http://android.myapp.com/myapp/detail.htm?apkName=com.yayun.gitlearning
喜欢的朋友可以关注我,多交流,谢谢。