使用 jackson 将 JSON 对象数组映射到 @RequestBody List<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10864049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:22:03  来源:igfitidea点击:

Map JSON array of objects to @RequestBody List<T> using Hymanson

jsonspringhibernateHymanson

提问by Thomas Buckley

I'm having issues using Hymanson to map a Javascript posted JSON array of hashes (Tag).

我在使用 Hymanson 映射 Javascript 发布的 JSON 哈希数组(标签)时遇到问题。


Here is the data received by the controller @RequestBody (It is send with correct json requestheader):


这是控制器@RequestBody 接收到的数据(使用正确的 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.

当我调试和查看“实体”值时,它显示为通用对象的 ArrayList,而不是我所期望的“标记”类型的对象列表。

How can I get Hymanson to map a passed array of objects to a list of obejcts of type 'Tag'?

如何让Hyman逊将传递的对象数组映射到“标签”类型的对象列表?

Thanks

谢谢

回答by StaxMan

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:

听起来 Spring 出于某种原因没有传递完整的类型信息,而是一个类型擦除的版本,就好像声明是类似List<?> tag. 我不知道可以做些什么来完全解决这个问题(可能需要 Spring 集成团队的一些东西),但一种解决方法是定义自己的类型,如:

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, Hymanson can figure out the Tagparameter.

并使用它。这将通过超类型声明保留泛型参数化,这样即使 Spring 只传递等效的TagList.class,Hymanson 也可以找出Tag参数。

回答by StaxMan

Another way to do this is to rather obtain an array than a List, as follows:

另一种方法是获取数组而不是列表,如下所示:

@RequestBody Tag[] entities

回答by user2812481

Hymanson requires a default constructor with no parameters on custom Objects, so you'll need to simply add a default constructor to your Tagclass.

Hymanson 在自定义对象上需要一个没有参数的默认构造函数,因此您只需将默认构造函数添加到您的Tag类中即可。

In your case simply add to your Tagclass:

在您的情况下,只需添加到您的Tag班级:

public Tag(){}