[英]How to parse JSON array objects textview 1 and textview 2
我的代碼適用於將json對象解析為單個textview,現在我想更改它以將第一個對象解析為文本Response,將第二個對象解析為text 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"
}
}
]
可以解決您的問題:
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);
其中“結果”是您的json數組字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.