我已经使用 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/