import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException;
// ----------------------------------------------------------------------------------------- // 4个编辑框 final EditText editName = (EditText) findViewById(R.id.editTextName); final EditText editAge = (EditText) findViewById(R.id.editTextAge); final EditText editAddr = (EditText) findViewById(R.id.editTextAddr); final EditText edit3q = (EditText) findViewById(R.id.editText3q); // ----------------------------------------------------------------------------------------- // 测试数据 final String simpleObject = "{ \"name\":\"阳光灿烂的日子\", \"age\":\"20\", \"addr\": \"http://www.cnblogs.com/cplusplusplus\"}"; final String arrayObject = "{ \"3q\": [ {\"IQ\":\"99\" }, {\"EQ\":\"99\" }, {\"AQ\":\"99\"} ]}"; // ----------------------------------------------------------------------------------------- // 响应按键 Button button = (Button) findViewById(R.id.buttonShow); button.setOnClickListener(new OnClickListener() { public void onClick(View t) { try { JSONObject jsimple = new JSONObject(simpleObject); // ----------------------------------------------------------------------------------------- // 取得名字字段 String name = jsimple.getString("name"); editName.setText(name); // ----------------------------------------------------------------------------------------- // 取得年龄字段 int age = jsimple.getInt("age"); editAge.setText(Integer.toString(age)); // ----------------------------------------------------------------------------------------- // 取得邮件字段 String addr = jsimple.getString("addr"); editAddr.setText(addr); // ----------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------- // 遍历数组 JSONObject jobject = new JSONObject(arrayObject); JSONArray jarray = jobject.getJSONArray("3q"); String str3q = ""; for (int i = 0; i < jarray.length(); i++) { JSONObject array = jarray.getJSONObject(i); // 取得JSONObject的名字 String name3q; name3q = array.keys().next().toString(); str3q += name3q + ":"; // 取得3q str3q += array.getString(name3q) + " "; } edit3q.setText(str3q); } catch (JSONException e) { throw new RuntimeException(e); } } }); // end Listener