如何解析JSON数组对象textview 1和textview 2

时间:2014-09-12 04:35:56

标签: java android json arrays jsonobject

我的代码适用于将json对象解析为单个textview现在我想更改它以将第一个对象解析为文本Response而第二个对象解析为Response2 这就是为什么我把for循环更改为i< = 1所以我只得到阵列的前2个结果我不需要其余的。 for循环适用于1个字段,但我认为我的if / else循环

有问题
try {
        // Parsing json array response
        // loop through each json object
        jsonResponse = "";
        jsonResponse2 ="";
        for (int i = 0; i <= 1; i++) {
          //int i  <= 1
            JSONObject person = (JSONObject) response
                            .get(i);

            String name = person.getString("name");

                if (i <=0){

                    jsonResponse += "Name: " + name + "\n\n";
                }

                else { jsonResponse2 += "Name: " + name + "\n\n";}

                }

            txtResponse.setText(jsonResponse);
            txtResponse2.setText(jsonResponse2);

JSON

[
    {
        "name": "Ravi Tamada",
        "email": "ravi8x@gmail.com",
        "phone": {
            "home": "08947 000000",
            "mobile": "9999999999"
        }
    },
    {
        "name": "Tommy",
        "email": "tommy@gmail.com",
        "phone": {
            "home": "08946 000000",
            "mobile": "0000000000"
        }
    },
    {
        "name": "Roy",
        "email": "roy8@gmail.com",
        "phone": {
            "home": "01944000000",
            "mobile": "6600000000"
        }
    },
    {
        "name": "Sami",
        "email": "sami69@gmail.com",
        "phone": {
            "home": "08006 104400",
            "mobile": "7700000000"
        }
    }
]

1 个答案:

答案 0 :(得分:1)

这可以解决您的问题:

                String name1,name2,name3,name4;
                JSONArray jArray=new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    if(i==0){
                        name1=jArray.getJSONObject(i).getString("name");
                        Log.e("Name First", name1);
                    }else if(i==1){
                        name2=jArray.getJSONObject(i).getString("name");
                        Log.e("Name Second", name2);
                    }else if(i==2){
                        name3=jArray.getJSONObject(i).getString("name");
                        Log.e("Name Third", name3);
                    }else if(i==3){
                        name4=jArray.getJSONObject(i).getString("name");
                        Log.e("Name Four", name4);
                    }
                }
               // txtResponse.setText(name1);
               // txtResponse2.setText(name2);

&#34;结果&#34;是你的json数组字符串。