我正在尝试用Java解决此问题。 我需要从URL读取JSON格式的学生数据,并在排序后将其输出。 该模型是:
[
{
"name": "string",
“lecturers”: [
{
"name": "string",
“subject”: "string"
}
]
}
]
以下是JSON数据的示例:
[
{
"name": “Jack”,
“lecturers”: [
{
"name": “Mr.Smith”,
“subject”: “Music”
},
{
"name": “Mr.Cooper”,
“subject”: “Physics”
},
{
"name": “Miss.Rae”,
“subject”: ""
}
]
},
{
"name": “Dan”,
“lecturers”: [
{
"name": “Miss.Jane”,
“subject”: “Physics”
},
{
"name": “Mr.Smith”,
“subject”: “Music”
},
{
"name": “Mr.JJ”
}
]
},
{
“lecturers”: [
{
"name": “Mr.Higgs”,
“subject”: “Art”
},
{
"name": “Mr.Jones”,
“subject”: “Chemistry”
}
]
}
]
输出应按字母顺序排序,如下所示:
Subject A
Lecturer X
Student E
Lecturer Y
Subject B
Lecturer A
Student C
Student D
到目前为止,我所做的是: 如下所示,使用Jackson库的ObjectMapper读取JSON数据。
public class Student {
String name;
List<Lecturer> lecturers;
}
public class Lecturer {
String name;
String Subject;
}
List<Student> student = objectMapper.readValue(new URL(“myUrl”), new TypeReference<List<Student>>(){});
如何进行分类?我应该使用Java比较器吗?不确定如何根据嵌套对象列表中的字段进行排序。还是应该以其他方式存储JSON数据并尝试排序? 另外,从示例中可以看到,应该处理空值。