2015-04-07 35 views
3

我已經使用spring引導創建了REST服務。最初我有多個參數(字符串和Ints),但有人建議我用json發送請求並自動將其轉換爲對象。但是,當我撥打以下REST服務,我得到以下錯誤:無法使用Spring引導將JSON轉換爲Java對象Rest服務

未能轉換類型的值「java.lang.String中」所需類型「xxxMobileCreatives」

@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

嘗試RequestBody MobileCreative movileCreative – faljbour

回答

4

你想要@RequestPart不是@RequestParam。根據文檔...

The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part. @RequestParam is likely to be used with name-value form fields while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML)