英文:
Return Hashmap from Spring Rest API
问题
我想使用这段代码从Rest API获取一些数据:
public Map<Integer, String> getCategoriesList() {
Map<Integer, String> list = new HashMap<>();
list.put(1, "Electronics");
list.put(2, "Outdoor and Sports");
list.put(3, "Home and Garden");
list.put(4, "Home appliances");
list.put(5, "Air conditioners and heaters");
list.put(6, "IT accessories");
list.put(7, "Photo and Video");
list.put(8, "TV Video and Gaming");
return list;
}
@GetMapping("categories")
public ResponseEntity<List<String>> getCategoriesList() {
return (ResponseEntity<List<String>>) categoriesService.getCategoriesList();
}
我得到错误:class java.util.HashMap cannot be cast to class org.springframework.http.ResponseEntity
以何种适当的方式将这些数据作为响应返回?
英文:
I want to use this code to get some data from Rest API:
public Map<Integer, String> getCategoriesList() {
Map<Integer, String> list = new HashMap<>();
list.put(1, "Electronics");
list.put(2, "Outdoor and Sports");
list.put(3, "Home and Garden");
list.put(4, "Home appliances");
list.put(5, "Air conditioners and heaters");
list.put(6, "IT accessories");
list.put(7, "Photo and Video");
list.put(8, "TV Video and Gaming");
return list;
}
@GetMapping("categories")
public ResponseEntity<List<String>> getCategoriesList() {
return (ResponseEntity<List<String>>) categoriesService.getCategoriesList();
}
I get error: class java.util.HashMap cannot be cast to class org.springframework.http.ResponseEntity
What is the appropriate way to return this data as a response?
答案1
得分: 2
你不能像那样将一个类型强制转换为另一个类型... 尝试这样做:
使用ResponseEntity包装:
@GetMapping("categories")
public ResponseEntity<Map<Integer, String>> getCategoriesList() {
return new ResponseEntity<Map<Integer, String>>(categoriesService.getCategoriesList(), HttpStatus.OK);
}
不使用ResponseEntity包装:
@GetMapping("categories")
@ResponseStatus(code = HttpStatus.OK)
public Map<Integer, String> getCategoriesList() {
return categoriesService.getCategoriesList();
}
因为这两种类型的映射都为Jackson所知(我假设您在Spring中用于序列化/反序列化的是Jackson),所以不需要做任何其他操作。
英文:
You cannot cast one type to another like that...try this
ResponseEntity type:
@GetMapping("categories")
public ResponseEntity<Map<Integer, String>> getCategoriesList() {
return new ResponseEntity<Map<Integer,String>>(categoriesService.getCategoriesList(), HttpStatus.OK);
}
Without ResponseEntity wrapper
@GetMapping("categories")
@ResponseStatus(code = HttpStatus.OK)
public Map<Integer, String> getCategoriesList() {
return categoriesService.getCategoriesList();
}
Since both types of map are known to jackson (I presume that's what you are using in spring for serialization/deserialization), no need to do anything more.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论