我正在尝试通过以JSON格式提供所需请求来使用邮递员提供服务:
{
"baseParam": {
"userId": "u1234"
},
"resource": {
"name": "resource"
}
}
还有一个多部分文件,如下面的邮递员屏幕所示
但是我得到了错误:
'无法将类型'java.lang.String'的值转换为所需的类型'SampleRequestObject';嵌套异常为java.lang.IllegalStateException:无法将[java.lang.String]类型的值转换为所需类型'
控制器
@RequestMapping(method = RequestMethod.POST, value = "/sample/resource",
produces = "application/json")
@ResponseBody
public final ResponseObject sampleResource(@RequestParam("request") final
SampleRequestObject requestObject,@RequestParam("file") final
MultipartFile file,BindingResult result ) throws IOException {
String success = “SUCCESS”;
requestObject.setFile(file);
String id=sampleService.sampleResourceService(resourceObject);
//sampleService Object has been autowired earlier in controller
return success;
}
}
SampleRequestObject –模型类
public class SampleRequestObject extends SampleMainObject {
@NotNull
@IsValid(baseParam = { "userId"})
private BaseParam baseParam;
@NotNull
private SampleResource resource; // ANOTHER OBJECT OF SAMPLE RESOURCE
CLASS
private MultipartFile file;
public SampleResource getResource() {
return resource;
}
public void setResource(SampleResource resource) {
this.resource = resource;
}
@Override
public Param getBaseParam() {
return baseParam;
}
public final void setBaseParam(final BaseParam baseParam) {
this.baseParam = baseParam;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
SampleServiceImpl.class中的函数(SampleService实现)
@Override
@Transactional
public final String sampleResourceService( SampleRequestObject
requestObject) {throws IOException
String Id=null;
try
{
MainResourceObject resourceObject = new MainResourceObject();
resourceObject.setActualName(requestObject.getFile()
.getOriginalFilename());
resourceObject.setName(requestObject.getResource().getName()); );
.
.
.
.
.
.
.
.
.
}
catch (Exception e) {
log.error("Service Execution failed",e);
}
}
我还尝试提供@ModelAttribute而不是@RequestParam。然后,可以输入控制器和服务,但是(在控制器中)requestObject的所有值都被填充为空值。因此,它将从服务实现中引发NullPointeException。
请提供解决方案。
答案 0 :(得分:1)
您可以尝试
public final ResponseObject sampleResource(SampleRequestObject request,
@RequestParam("file") final MultipartFile file,
BindingResult result ) throws IOException {
...
我刚刚删除了@RequestParam
并将变量更改为request