当前位置: 首页 > 知识库问答 >
问题:

无法将“java.lang.String”类型的值转换为所需的模型对象类型

薛欣德
2023-03-14

我正试图通过提供JSON格式的所需请求来使用postman来访问一个服务:

 {
    "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中的函数(SampleServiceImplemetation)

    @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。

请提供一个解决方案。

共有1个答案

锺离逸春
2023-03-14

你能试试这个吗

public final ResponseObject sampleResource(SampleRequestObject request,
       @RequestParam("file") final MultipartFile file,
       BindingResult result ) throws IOException {
...

我刚刚删除了@requestparam并将变量改为request

 类似资料: