将对象的 JSON 数组映射到 @RequestBody List<T>;使用杰克逊 [英] Map JSON array of objects to @RequestBody List<T> using jackson
问题描述
我在使用 Jackson 映射 Javascript 发布的 JSON 哈希数组(标签)时遇到问题.
I'm having issues using Jackson to map a Javascript posted JSON array of hashes (Tag).
这是控制器@RequestBody 收到的数据(使用正确的 json requestheader 发送):
Here is the data received by the controller @RequestBody (It is send with correct json requestheader):
[{name=tag1}, {name=tag2}, {name=tag3}]
这是控制器:
@RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags")
@ResponseStatus(HttpStatus.CREATED)
public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final List<Tag> entities)
{
Purchase purchase = purchaseService.getById(purchaseId);
Set<Tag> tags = purchase.getTags();
purchaseService.updatePurchase(purchase);
}
当我调试和查看实体"值时,它显示为通用对象的 ArrayList,而不是我期望的标签"类型的对象列表.
When I debug and view the 'entities' value it shows as an ArrayList of generic objects, not as a list of objects of type 'Tag' as I would expect.
如何让 jackson 将传递的对象数组映射到标签"类型的对象列表?
How can I get jackson to map a passed array of objects to a list of obejcts of type 'Tag'?
谢谢
推荐答案
听起来 Spring 由于某种原因没有传递完整的类型信息,而是一个类型擦除的版本,就好像声明是类似 List<;?>标签
.我不知道可以做些什么来完全解决这个问题(可能需要 Spring 集成团队的一些东西),但一种解决方法是定义你自己的类型,如:
It sounds like Spring is not passing full type information for some reason, but rather a type-erased version, as if declaration was something like List<?> tag
. I don't know what can be done to fully resolve this (may need something from Spring integration team), but one work-around is to define your own type like:
static class TagList extends ArrayList<Tag> { }
并改用它.这将通过超类型声明保留泛型参数化,这样即使 Spring 只传递等效的 TagList.class
,Jackson 也可以找出 Tag
参数.
and use that instead. This will retain generic parameterization through super-type declarations so that even if Spring only passes equivalent of TagList.class
, Jackson can figure out the Tag
parameter.
这篇关于将对象的 JSON 数组映射到 @RequestBody List<T>;使用杰克逊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!