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

标签 java json rest spring-boot

我已经使用 spring boot 创建了一个 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"}

我的类 MobileCreative 有一个与 json 格式相同的构造函数。我是否需要向类 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)

关于java - 无法使用 Spring 引导 Rest 服务将 JSON 转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481640/

相关文章:

java - 从 URL 更改动态图像

android - 使用 GSON 时的 Proguard 问题

python - 如何使用 urllib2 在 Python 中发送 header

php - 在 Objective C 中从 URL 下载 JSON 的简单方法

c# - HttpClient 抛出 "An error occurred while sending the request."

java - 我的 Servlet 和 @FormDataParam Jersey 有问题

java - 计数并显示大写字母、小写字母和数字

java - 如何不断提示用户输入新词

java - 如何让一个角色走主角路线? LIBGDX/Java

c# - 什么是 'api_key' 以及如何正确使用它