Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 564
Thomas Buckley Avatar asked Jun 02 '12 16:06

Thomas Buckley


1 Answers

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.

like image 183
StaxMan Avatar answered Jan 03 '23 18:01

StaxMan