我正在尝试通过以 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;
}
}
样本请求对象 – 模型类
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 Implemetation( 中的函数
@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 的所有值(在控制器中(都填充为 null 值。因此,它从服务实现中抛出 NullPointeException。
请提供解决方案。
你能试试这个吗
public final ResponseObject sampleResource(SampleRequestObject request,
@RequestParam("file") final MultipartFile file,
BindingResult result ) throws IOException {
...
我刚刚删除了@RequestParam
并将变量更改为request