gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:32:56 25 4
gpt4 key购买 nike

我的代码适用于将 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"
}
}
]

最佳答案

这可以解决您的问题吗:

                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);

其中“result”是您的 json 数组字符串。

关于java - 如何解析JSON数组对象textview 1和textview 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25800815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com