无法使用 Spring 引导 Rest 服务将 JSON 转换为 Java 对象

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

我已经使用 spring 启动创建了一个 REST 服务。最初我有多个参数(Strings 和 Ints),但建议我在 json 中发送请求并自动将其转换为对象。但是当我调用以下 REST 服务时,出现以下错误:

无法将类型 'java.lang.String' 的值转换为所需类型 '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);
    }

我想知道为什么它认为输入是一个字符串,当输入是以下内容时 JSON:

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

我的 class MobileCreative 有一个与 json 格式相同的构造函数。我是否需要向 class MobileCreative 添加任何注释,因为我正在查看的示例没有任何注释?

你想要 @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)