我使用spring boot创建了一个REST服务。最初我有多个参数(字符串和Ints),但有人建议我在json中发送请求并自动将其转换为对象。但是,当我调用以下REST服务时,我收到以下错误:
无法将'java.lang.String'类型的值转换为必需类型'x.x.x.MobileCreatives'
@RequestMapping(method = RequestMethod.POST, value = "/creative")
public @ResponseBody void uploadCreative(@RequestParam("mobileCreatives") MobileCreatives mobileCreatives,
@RequestParam("file") MultipartFile file){
logger.trace("Sending creative to DFP");
mobileCreatives.setFile(file);
dfpAssetsManager.createCreative(mobileCreatives);
}
我想知道为什么输入是一个字符串,当输入是以下JSON时:
{"networkCode":6437988,"iO":"test345345","name":"test4354","advertiserId":11659988,"clickThroughUrl":"test.com"}
我的类MobileCreative有一个与json格式相同的构造函数。我是否需要在MobileCreative类中添加任何注释,因为我看到的一个例子没有任何注释?
答案 0 :(得分:4)
您希望@RequestPart
不是@RequestParam
。根据文件......
主要区别在于当method参数不是String时, @RequestParam依赖于通过已注册的Converter或类型转换 PropertyEditor,而@RequestPart依赖于HttpMessageConverters 考虑请求的“Content-Type”标题 部分。 @RequestParam可能与名称 - 值表单字段一起使用 而@RequestPart可能会与包含更多内容的部分一起使用 复杂内容(例如JSON,XML)