简体   繁体   中英

Unable to convert JSON to Java Object using Spring boot Rest service

I have created a REST service using spring boot. Initially I had multiple parameters (Strings and Ints), but it was suggested that I send the request in json and automatically convert it to an object. But when I call the following REST service I get the following error:

Failed to convert value of type 'java.lang.String' to required type '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);
    }

I would like to know why it is thinking that the input is a string, when the input is the following JSON:

{"networkCode":6437988,"iO":"test345345","name":"test4354","advertiserId":11659988,"clickThroughUrl":"test.com"}

My class MobileCreative has a constructor that is in the same format as the json. Do I need to add any annotations to the class MobileCreative becasue an example I was looking at didn't have any?

You want @RequestPart not @RequestParam . Per the documentation ...

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 (eg JSON, XML)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM