Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 'x.x.x.MobileCreatives'

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

like image 909
DarrenCibis Avatar asked Apr 24 '26 05:04

DarrenCibis


1 Answers

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 (e.g. JSON, XML)

like image 79
ikumen Avatar answered Apr 25 '26 18:04

ikumen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!