【问题标题】:Unable to convert JSON to Java Object using Spring boot Rest service无法使用 Spring Boot Rest 服务将 JSON 转换为 Java 对象
【发布时间】:2015-06-11 11:06:12
【问题描述】:

我已经使用 spring boot 创建了一个 REST 服务。最初我有多个参数(字符串和整数),但建议我以 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 类添加任何注释,因为我正在查看的示例没有任何注释?

【问题讨论】:

  • 试试 RequestBody MobileCreative movileCreative

标签: java json rest spring-boot


【解决方案1】:

你想要@RequestPart 而不是@RequestParam。根据文档...

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

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 2017-08-23
    • 1970-01-01
    • 2021-05-17
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多