本文介绍了将JSON对象数组映射到@RequestBody List< T>使用杰克逊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是收到的数据由控制器@RequestBody(使用正确的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长期purchaseId,@RequestBody final List< Tag>实体)
{
购买购买= purchaseService.getById(purchaseId);
设置< Tag> tags = purchase.getTags();
purchaseService.updatePurchase(购买);
}
当我调试并查看实体值时,它显示为一个ArrayList通用对象,而不是我期望的'Tag'类型的对象列表。
如何获得杰克逊映射通过的数组对象的类型为'Tag'类型的列表?
谢谢 解决方案
List<?>标签。我不知道该怎么做才能完全解决这个问题(可能需要Spring集成团队的一些东西),但一个解决方法是定义自己的类型,如:
静态类TagList扩展ArrayList< Tag> {}
并改为使用它。这将通过超类型声明保留通用参数化,这样即使Spring只通过等价的 TagList.class
,杰克逊也可以计算出 Tag 参数。
I'm having issues using Jackson to map a Javascript posted JSON array of hashes (Tag).
Here is the data received by the controller @RequestBody (It is send with correct json requestheader):
[{name=tag1}, {name=tag2}, {name=tag3}]
Here is the controller:
@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);
}
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.
How can I get jackson to map a passed array of objects to a list of obejcts of type 'Tag'?
Thanks
解决方案
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> { }
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>使用杰克逊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!