我想使用 java.util.stream 修改嵌套 json (Map<String, Object>) 中的数据。
这是 Json 数据
{
"schoolId": "10928391",
"schoolName": "school A",
"teachers" : [
{
"teacherId": "00001",
"teacherName:": "teacher A",
"subject": "Computer Science",
"lectures": [
{
"id": "CS102",
"name": "Algorithm"
},
{
"id": "CS330",
"name": "Data Communications and Networking"
}
]
},
{
"teacherId": "00002",
"teacherName:": "teacher B",
"subject": "Computer Science",
"lectures": [
{
"id": "CS103",
"name": "Data Structure"
},
{
"id": "CS104",
"name": "Data Structures in C++"
}
]
},
{
"teacherId": "00003",
"teacherName:": "teacher C",
"subject": "Computer Science",
"lectures": [
{
"id": "CS100",
"name": "Introduction to Programming (Java)"
},
{
"id": "CS401",
"name": "Object Oriented Programming"
}
]
}
]
}
--
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> schoolInfo = mapper.converValue(restTemplate.exchange(url, HttpMethod.GET, .... ).getBody(), HashMap.class);
上面的 Json 数据在 schoolInfo 里面
我要访问和修改的数据是讲座。我试图修改讲座(数组)中的所有元素。
例如,
"lectures": [
{
"id": "CS102",
"name": "Algorithm"
},
{
"id": "CS330",
"name": "Data Communications and Networking"
}
]
替换讲座数据中的所有讲座信息,如下所示。
"lectures": [
{
"lectureId": "CS102",
"lectureName": "Algorithm",
"lectureRoom": "Room A-1"
},
{
"lectureId": "CS330",
"lectureName": "Data Communications and Networking",
"lectureRoom": "Room A-2"
}
]
使用地图,过滤器我可以访问“教师”对象,但我不知道如何在“教师”中获取“讲座”对象
System.out.println(jsonMap.entrySet().stream()
.filter(map -> map.getKey().equals("teachers")).collect(Collectors.toList()).toString());
任何建议都会非常有帮助!