我创建了一个带有Map
@RequestMapping(value = "upload", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(@RequestParam("file") MultipartFile file,
@RequestParam("name") String name,
@RequestParam("campaignAppItemId") Long campaignAppItemId,
@RequestParam("fileColumnHeaders") Map<String,Integer> fileColumnHeaders) throws Exception {
if (file == null)
return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
contactService.handleContactsFile(file, name, campaignAppItemId,fileColumnHeaders);
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
我正试图通过邮递员打电话给这个
我像在SS中那样在Body-> Form Data中传递了fileColumnHeaders
然后我在邮递员那里收到了这样的消息
无法将类型“ java.lang.String”的值转换为所需的类型“ java.util.Map”;嵌套的异常是java.lang.IllegalStateException:无法将“ java.lang.String”类型的值转换为所需的“ java.util.Map”类型:找不到匹配的编辑器或转换策略。
有人知道为什么会收到此消息吗? 如何在Rest API请求中将地图作为参数传递? 我们如何通过邮递员传递地图?
任何帮助都会帮助
答案 0 :(得分:2)
对于Maps和其他非平凡的数据类型和对象,您可以使用@RequestBody
而不是@RequestParam
-这样,spring会将代表您的map参数的JSON映射到域对象,该对象随后可以序列化并可以转换为java对象。
答案 1 :(得分:2)
首先,创建DTO对象以从请求中获取所有数据。
public class FormDataDTO {
private MultipartFile file;
private String name;
private Long campaignAppItemId;
private Map<String,Integer> fileColumnHeaders;
// getters, setters
}
第二,您可以从请求中映射FormDataDTO,而无需任何注释:
@RequestMapping(value = "upload", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(FormDataDTO formDataDTO){
// your logic code here
}
答案 2 :(得分:0)
我认为这可行:
@RequestMapping(value = "upload/{fileColumnHeaders}", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(@RequestParam("file") MultipartFile file,
@RequestParam("name") String name,
@RequestParam("campaignAppItemId") Long campaignAppItemId,
@MatrixVariable Map<String,Integer> fileColumnHeaders) throws Exception {
if (file == null)
return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
contactService.handleContactsFile(file, name, campaignAppItemId,fileColumnHeaders);
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
将所有其他参数放入正文中,但是将fileColumnHeaders添加到网址中,如下所示:
/upload/firstName=1;lastName=2;address=3;phone=4
您还需要以下额外配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
答案 3 :(得分:0)
...或者只是创建一个转换器:
@Component
@RequiredArgsConstructor
public class StringToMapConverter implements Converter<String, Map<String, Object>> {
private final ObjectMapper objectMapper;
@Override
public Map<String, Object> convert(String source) {
try {
return objectMapper.readValue(source, new TypeReference<Map<String, String>>() {
});
} catch (final IOException e) {
return null;
}
}
}