首页 文章

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

提问于
浏览
3

我使用spring boot创建了一个REST服务 . 最初我有多个参数(字符串和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"}

我的类MobileCreative有一个与json格式相同的构造函数 . 我是否需要在MobileCreative类中添加任何注释,因为我看到的一个例子没有任何注释?

1 回答

  • 4

    你想@RequestPart不是 @RequestParam . 根据文件......

    主要区别在于,当method参数不是String时,@ RequestParam依赖于通过已注册的Converter或PropertyEditor进行类型转换,而@RequestPart依赖于HttpMessageConverters,并考虑请求部分的“Content-Type”标头 . @RequestParam可能与名称 - 值表单字段一起使用,而@RequestPart可能与包含更复杂内容的部分一起使用(例如JSON,XML)

相关问题