JSONObject & 取得Key名 & 遍歷數組


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM