英文:
class java.util.ArrayList cannot be cast to class org.springframework.util.MultiValueMap
问题
[
{
"name": "巴布亚新几内亚",
"value": "PG"
},
{
"name": "美国",
"value": "US"
},
...
]
public Map<String, Object> getCountryNameCodeList() {
String[] countryCodes = Locale.getISOCountries();
Map<String, Object> list = new HashMap<>();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
list.put(obj.getDisplayCountry(), obj.getCountry());
}
return list;
}
@GetMapping("shipping_countries")
public ResponseEntity<List<Map<String, String>>> getShippingCountries() {
Map<String, Object> list = countriesService.getCountryNameCodeList();
List<Map<String, String>> countries = new ArrayList<>();
for (Map.Entry<String, Object> entry : list.entrySet()) {
Map<String, String> country = new HashMap<>();
country.put("name", entry.getKey());
country.put("value", entry.getValue().toString());
countries.add(country);
}
return new ResponseEntity<>(countries, HttpStatus.OK);
}
出现错误的原因是在返回ResponseEntity
时,您尝试将dtos
(类型为ArrayList
)转换为MultiValueMap
,这是不正确的。我已经根据您的代码对其进行了修复,现在应该能够获得您所期望的 JSON 响应,并且不会再出现错误。
英文:
I want to generate a JSON response which includes inner JSON Objects. I tried this:
public Map<String, Object> getCountryNameCodeList() {
String[] countryCodes = Locale.getISOCountries();
Map<String, Object> list = new HashMap<>();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
list.put(obj.getDisplayCountry().toString(), obj.getCountry());
}
return list;
}
Rest Api:
@GetMapping("shipping_countries")
public ResponseEntity<Set<Map.Entry<String, Object>>> getShippingCountries() {
Map<String, Object> list = countriesService.getCountryNameCodeList();
List<KeyValueDTO> dtos = new ArrayList();
for(Map.Entry<String, Object> value: list.entrySet()) {
KeyValueDTO dto = new KeyValueDTO();
dto.setKey(value.getKey());
dto.setValue(value.getValue().toString());
dtos.add(dto);
}
return new ResponseEntity<Set<Map.Entry<String, Object>>>((MultiValueMap<String, String>) dtos, HttpStatus.OK);
}
I want to get this response:
[
{
name: "Papua New Guinea",
value: "PG"
},
{
name: "Unites States",
value: "US"
},
....
]
But I get this error:
class java.util.ArrayList cannot be cast to class org.springframework.util.MultiValueMap (java.util.ArrayList is in module java.base of loader 'bootstrap'; org.springframework.util.MultiValueMap is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @6267c3bb)
How I can fix this issue?
答案1
得分: 1
似乎您正在将一个列表 List<KeyValueDTO>
强制转换为一个多映射 (MultiValueMap<String, String>)
。它们是完全不同的类型 - 列表不是映射。因此,在您的帖子中出现了异常。尝试在不进行转换的情况下返回该值。
英文:
It seems you are typecasting List<KeyValueDTO>
a list into (MultiValueMap<String, String>)
a multimap. They are totally different types - a list is not a map. Hence, the exception in your post. Try to return the value without the cast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论