我有以下格式的json对象。
[
{
"StudentID": 1,
"StudentMarks": [
{
"StudentID": 1,
"English": 1500000,
"Maths": 15,
"Science": 15,
"History": 10,
"TestID": 1,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 1,
"English": 155,
"Maths": 1578,
"Science": 15,
"History": 10,
"TestID": 2,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 1,
"English": 155,
"Maths": 15,
"Science": 150,
"History": 10,
"TestID": 3,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 1,
"English": 150,
"Maths": 15,
"Science": 15,
"History": 10,
"TestID": 6,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 1,
"English": 155,
"Maths": 1578,
"Science": 15,
"History": 10,
"TestID": 7,
"Date": "2018-01-29T14:38:11.01"
}
]
},
{
"StudentID": 2,
"StudentMarks": [
{
"StudentID": 2,
"English": 155,
"Maths": 151,
"Science": 15,
"History": 1025,
"TestID": 4,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 2,
"English": 1551,
"Maths": 15,
"Science": 15,
"History": 100,
"TestID": 5,
"Date": "2018-01-29T14:38:11.01"
},
{
"StudentID": 2,
"English": 1,
"Maths": 1,
"Science": 15,
"History": 10,
"TestID": 8,
"Date": "2018-01-29T14:38:11.01"
}
]
}
]
在此,我需要在android自定义列表视图中列出学生ID和最新的测试标记,
要提取每个学生证,我正在使用
JSONArray myListsAll= new JSONArray(jsonStr);
for(int i=0;i<myListsAll.length();i++)
{
JSONObject c= (JSONObject) myListsAll.get(i);
History= c.getString("History");
Science= c.getString("Science");
Maths= c.getString("Maths");
English= c.getString("English");
}
但是我想要学生证并标记最新测试的详细信息。我想到从“ StudentMarks”中获取最大“ TestId”的数组元素。怎么做?
最佳答案
假设您能够遍历并且使用下面的代码行获取所有StudentMarks
JSONArray myListsAll= new JSONArray(jsonStr);
for(int i=0;i<myListsAll.length();i++)
{
JSONObject obj= (JSONObject) myListsAll.get(i);
History= obj.getString("History");
...
}
然后,IMO,您可以在获得最大
TestId
时存储值,并为获得最大TestId
,可以将其初始化为最小值,每当获得更大的值时,将所有值覆盖为最新值。JSONArray myListsAll= new JSONArray(jsonStr);
int test_id = Integer.MIN_VALUE;
for(int i=0;i<myListsAll.length();i++)
{
JSONObject obj= (JSONObject) myListsAll.get(i);
int curTestId = obj.getInt("TestID");
if (test_id < curTestId)
{
History= obj.getString("History");
Science= obj.getString("Science");
Maths= obj.getString("Maths");
English= obj.getString("English");
test_id = curTestId;
}
}
System.out.print("Maximum Test Id for this student :" + test_id );
关于java - 提取特定的json数组元素,比较所有数组元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48519498/