我开始玩杰克逊 json,但我卡住了。我知道 Json 返回了:
[
{
"id": "1",
"groups": [
{
"id": "1",
"name": "Group99",
"students": [
{
"studentId": "1"
},
{
"studentId": "2"
},
{
"studentId": "3"
}
],
"schoolId": 10
},
{
"id": "2",
"name": "Group100",
"students": [
{
"studentId": "1"
},
{
"studentId": "2"
},
{
"studentId": "3"
}
],
"schoolId": 10
}
]
}
]
我想得到一个没有学生数组的 JSON。像这样
[
{
"id": "1",
"groups": [
{
"id": "1",
"name": "Group99",
"schoolId": 10
},
{
"id": "2",
"name": "Group100",
"schoolId": 10
}
]
}
]
现在我从数据库中得到一个列表,我创建了一个 ObjectMapper,它只返回 ObjectMapper.writeValueAsString(list)。如何修改列表,以便在杰克逊的 JSON 中排除学生数组?
编辑 Java 代码
我现在拥有的Java代码是
List<Assessment> assessments = (List<Assessment>) assessmentRepository.findGroupsByUsernameAndAssessmentId(username, assessmentId);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
// create the new JSON
List<String> groups = new ArrayList<>();
for(int i = 0; i <= assessments.size() - 1; i++){
for(int k = 0; k < assessments.get(i).getGroups().length; k++){
// create the String with only the wanted information
}
}
return mapper.writeValueAsString(groups);
我不确定这是否是正确的方法,我希望有一种更简单的方法
更新我使用 HashMap 修复了它。Java 代码可以在下面找到。让我知道这是一个好方法还是有更好的方法
Assessment assessment = (Assessment) assessmentRepository.findGroupsByUsernameAndAssessmentId(username, assessmentId);
// 2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
// create the new JSON
ArrayList<Object> jsonWithoutTeacherAndStudents = new ArrayList<Object>();
HashMap<String, String> jsonKeyAndValueMap = new HashMap<>();
GroupSummary[] summary = assessment.getGroups();
for (int i = 0; i < assessment.getGroups().length; i++) {
jsonKeyAndValueMap.put("id", summary[i].getId());
jsonKeyAndValueMap.put("name", summary[i].getName());
jsonKeyAndValueMap.put("schoolId", Integer.toString(summary[i].getSchoolId()));
jsonWithoutTeacherAndStudents.add(mapper.writeValueAsString(jsonKeyAndValueMap));
}
return jsonWithoutTeacherAndStudents.toString();