List < Response > Data = new ArrayList < Response > ();
Response object = null;
JSONObject documentRoot = new JSONObject(result);
JSONArray documentChild = documentRoot.getJSONArray("Main");
JSONArray allergyArray = null;
JSONArray vitalsArray = null;
for (int i = 0; i < documentChild.length(); i++) {
child = documentChild.getJSONObject(i);
if (Condition1) {
allergyArray = child.getJSONArray("Allergy");
} else if {
vitalsArray = child.getJSONArray("Vitals");
}
}
object = new Response(); // POJO class
if (null != allergyArray) {
for (int i = 0; i < allergyArray.length(); i++) {
object.setCap(allergyArray.getJSONObject(i).getString("Cap"));
object.setRea(allergyArray.getJSONObject(i).getString("Rea"));
}
}
if (null != vitalsArray) {
for (int i = 0; i < vitalsArray.length(); i++) {
object.setName(vitalsArray.getJSONObject(i).getString("Name"));
object.setMedic(vitalsArray.getJSONObject(i).getString("Medic"));
}
}
Data.add(object);
当我尝试迭代并打印结果时,只打印最后添加的项目。
public void onLoadComplete(List < Response > item) {
for (int i = 0; i < item.size(); i++) {
Log.d("Get", item.get(i).getCap()); // I get only the last item which is added.
}
}
为什么传递给onLoadComplete函数的List对象只包含添加到POJO类的最后一项。
答案 0 :(得分:1)
在你的循环中,你在每次迭代中设置相同对象的值(cap,rea,name&amp; medic),这意味着迭代完成后只会设置最后一个值。
对于创建新对象所需的每个值。这是一个基本示例,为了安全起见,需要添加一些检查:
if (null != allergyArray && null != vitalsArray)
{
for (int i = 0; i < allergyArray.length() && i < vitalsArray.length(); ++i)
{
object = new Response(); // POJO class
object.setCap(allergyArray.getJSONObject(i).getString("Cap"));
object.setRea(allergyArray.getJSONObject(i).getString("Rea"));
object.setName(vitalsArray.getJSONObject(i).getString("Name"));
object.setMedic(vitalsArray.getJSONObject(i).getString("Medic"));
Data.add(object);
}
}