如何从一个JSONArray获得最后一个对象
问题描述:
我有一个listView
,我为每个主题显示students attendance
,我解析JSON
,直到secondlast
为止。为此,在计数我确实返回attendanceBeanList.size()-1
。见下面的代码。 我已经这样做了:如何从一个JSONArray获得最后一个对象
private List<TotalAttendance_Bean> attendanceBeanList;
public TotalAttendanceAdapter(Activity activity, List<TotalAttendance_Bean> attendanceBeanList)
{
super();
this.activity = activity;
this.attendanceBeanList = attendanceBeanList;
}
@Override
public int getCount() {
return attendanceBeanList.size()-1;
}
现在,当我要得到最后一个对象,我卡住了。我必须为每位学生提供Total考勤。为此,我必须从JSONArray
以下获得最后一个对象。
这是我的JSON:
[
{
"subject_name": "English-I",
"total_classes": "2",
"total_attended": "2",
"percentage": "100"
},
{
"subject_name": "English-I",
"total_classes": "2",
"total_attended": "2",
"percentage": "100"
},
{
"subject_name": "English-I",
"total_classes": "2",
"total_attended": "2",
"percentage": "100"
},
{
"subject_name": "English-I",
"total_classes": "2",
"total_attended": "2",
"percentage": "100"
},
{
"total_attendance": 90%
}
]
这是我的XML。
答
您可以获取您的total_attendance
解析所有students
记录
JSONArray obj = new JSONArray(yourStringResponse);
// get the last object
JSONObject tot_obj = obj.getJSONObject(obj.length()-1);
// get String from last object
String tot_str = tot_obj.optString("total_attendance");
注后:optString
将您的数据转换为String
否则会给空string
像""
。
现在你可以在你的Activity
的TextView
像
yourTextView.setText(tot_str);
显示数据,你可以通过你的tot_str
到Adapter
如果你需要
public TotalAttendanceAdapter(Activity activity
, List<TotalAttendance_Bean> attendanceBeanList
, String tot)
{
super();
this.activity = activity;
this.attendanceBeanList = attendanceBeanList;
this.tot = tot;
}
你张贴的JSON是无效的,检查验证程序并更正代码 – OBX
先生我也检查过,它显示“有效的JSON”。我们不能在这个JSON中做什么 –