[英]org.springframework.data.mapping.MappingException: Cannot convert type class java.util.ArrayList into an instance of class java.lang.Object
[英]class java.util.ArrayList cannot be cast to class org.springframework.util.MultiValueMap
我想生成一个包含内部 JSON 对象的 JSON 响应。 我试过这个:
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;
}
休息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);
}
我想得到这个回应:
[
{
name: "Papua New Guinea",
value: "PG"
},
{
name: "Unites States",
value: "US"
},
....
]
但我收到此错误:
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)
我该如何解决这个问题?
看来您正在将List<KeyValueDTO>
列表类型转换为(MultiValueMap<String, String>)
映射。 它们是完全不同的类型——列表不是地图。 因此,您帖子中的例外情况。 尝试在没有强制转换的情况下返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.