[解决!溶液反映在代码]
我正在使用Spring Boot开发一个项目,在这里我需要包含JSON对象组的数组。它看起来像这样的例子:
{
"Spring20": [
{
"CSCXXX": "Machine Learning",
. . .
},
{
"CSCXXX": "Computer Vision",
. . .
}
],
"Fall20": [
{
"EEXXX": "Electronics",
. . .
}
]
}
我尝试使用一个Map,该Map存储一个用于Array主题名称的String和一个用于容纳所有类对象的List。这位于服务类中。
HashMap<String, List<Courses>> courseList = new HashMap<String, List<Courses>>();
[修改为适合的解决方案]
服务
public void add( Map<String, List<Courses>> course) {
course.forEach((string, list) -> {
if(course_list.containsKey(semester)) {
course_list.get(semester).addAll(course);
} else {
course_list.put(semester, course);
}
});
}
public void edit(String semester, String id, Courses courses) {
// Get the Course list from the Map
List<Courses> updatedCourse = course_list.get(semester);
// Loop and find the matching object within the list
for(int i=0; i<updatedCourse.size(); i++){
if (updatedCourse.get(i).getID().equals(id)){
// Once object found, update its values in the list
updatedCourse.get(i).set(course.getSubject())
. . .
// Finally, replace the list within the map
course_list.replace(semester, updatedCourse);
}
}
}
控制者
@RequestMapping(method=RequestMethod.POST, value="/add")
public void addCourse(@RequestBody Map<String, List<Courses>> course) {
service.addTest(course);
}
@RequestMapping(method=RequestMethod.PUT, value="/edit/{semster}/{id}")
public void addCourse(@PathVariable("semester") String semester, @PathVariable("id") String id, @RequestBody Courses course) {
service.editTest(semester, id, course);
}
首次添加JSON并获得正确的JSON结构时,一切都按预期工作。但是,添加和编辑值时会变得很复杂。
PUT: localhost:8080/edit/Spring20/
>> "message": "Missing URI template variable 'semester' for method parameter of type String",
我尝试研究此问题,但没有找到任何有用的链接或示例,人们无法使用Spring Boot对其进行JSON分类和组织。如果有什么可以帮助的,请在下面评论。
编辑下面的解决方案有助于修复这些错误。希望这篇文章对任何可能遇到相同问题的人有所帮助!
这是我在MongoDB上使用Map <>的另一篇文章。在MongoDB Spring Boot中嵌套在对象内的Array对象上的CRUD操作
看一下以下内容:
每当我将单个对象添加到数组时,它就会替换数组中先前的所有对象。例如,我在“ Spring 2020”数组中有两个对象。如果我使用addCourse()发出另一个POST请求,则两个对象都将被替换。
问题是您正在使用map.put()
。使用此方法时,如果映射先前包含键的映射,则旧值将替换为指定值。因此,您的旧值将被删除。
解决方案是获取并更新现有条目。
public void add( Map<String, List<Courses>> course) {
course.forEach((semester, list) -> {
if(courseList.contains(semester)) {
courseList.get(semester).addAll(list); // Note, list accepts duplicates
} else {
courseList.put(semester, list);
}
});
}
如果我尝试使用邮递员进行编辑,则会出现一些异常。PUT:localhost:8080 / edit / Spring20 /“ message”:“缺少类型为String的方法参数的URI模板变量'semester'”,
问题是您的路径变量名称semester与url semster中的名称不匹配。因此,Missing URI template variable 'semester'
@RequestMapping(method=RequestMethod.PUT, value="/edit/{semester}/{id}")
public void addCourse(@PathVariable("semester") String semester, @PathVariable("id") String id, @RequestBody Courses course) {
service.editTest(semester, course);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句