[英]Spring (4.2.6) + Jackson (2.8.4) + Generic Type : java.util.LinkedHashMap cannot be cast to
After two days, I'm stuck with the following... 两天后,我陷入了以下困境...
If I specify the type in the controller, it works: 如果我在控制器中指定了类型,它将起作用:
@RestController
public class FooController {
@RequestMapping(method = RequestMethod.POST)
protected ResponseModel bar(@Valid @RequestBody Foo foo) {
// here I have foo of type Foo
}
}
However, if I try to take advantage of generics, it doesn't work: 但是,如果我尝试利用泛型,则无法使用:
public class Base<U> {
@RequestMapping(method = RequestMethod.POST)
protected ResponseModel bar(@Valid @RequestBody U entity) {
// here I get java.util.LinkedHashMap instead of U
// which, in the FooController, should be Foo
}
}
@RestController
public class FooController extends Base<Foo> {
}
Looking at the logs, when it hits the controller with defined type I get: 查看日志,当它到达定义类型的控制器时,我得到:
Read [class com...Foo] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cee662]
While at the generic one: 在通用的时候:
Read [U] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cee662]
Q: What should I do to take advantage of the Generic Type, and to be able to cut the repeated code from the controllers? 问:我应该怎么做才能利用通用类型,并能够从控制器中删除重复的代码?
Note: this is NOT a duplicate, since all the other questions are about List<T>
or from an issue on ~2.6.* 注意:这不是重复的,因为所有其他问题都与
List<T>
或者与〜2.6。*有关。
Addendum: Yuri-M-Dias suggested downgrading, which I did, so 2.5.5 works with a Generic Type, but 2.8.4 doesn't. 附录: Yuri-M-Dias建议降级,我这样做了,所以2.5.5适用于泛型类型,但2.8.4不能。 (At least for now I have a bad and good revision to work with...)
(至少到目前为止,我的修订版本不佳...)
Going further into the downgrade... 进一步降级...
I found out that the revision 2.7.9 is a good one, I get Foo
out of U
, while on the 2.8.0 I get the LinkedHashMap<K,V>
... maybe I missed something from the 2.8.0 release ? 我发现版本2.7.9是一个很好的版本,我从
U
删除了Foo
,而在版本2.8.0中,我得到了LinkedHashMap<K,V>
...也许我错过了版本2.8.0中的内容 ?
I don't know if you happened to see Generic Controller in Spring MVC , but it may be instructive. 我不知道您是否碰巧在Spring MVC中看到Generic Controller ,但这可能很有帮助。 Still, I'm not happy with what I'm about to describe, because I see what you're trying to do above.
不过,我对我要描述的内容还是不满意,因为我在上面已经看到了你想做的事情。 Additionally, I can't give you the reason behind the possible "necessity."
此外,我无法为您提供可能的“必要性”背后的原因。 Hopefully someone else will be able to fill that it.
希望其他人能够填补它。
@RestController
public class FooController extends Base<Foo> {
@RequestMapping(method = RequestMethod.POST)
protected ResponseModel bar(@Valid @RequestBody Foo foo) {
super.bar(foo);
}
}
Seems like that should make everything happy. 似乎应该使一切变得快乐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.