Spring MVC @RequestBody into an Interface instead

2019-08-02 19:06发布

问题:

Folks,

This code snipped works:

@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<List<Member>> findByMemberKeyOrUniqueMemberId(

Note that "Member" is an interface, not a class.

This does not work.

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> save(@RequestBody final List<Member> members) {

So I can turn Members into JSON but I can't receive JSON into Members. If I change save's argument from List to a List of one of Member's classes then it works fine but it really messes up my code.

How can I fix this?

回答1:

Jackson can not (it's infeasible) guess which Member implementation to use to deserialize the JSON.

Jackson offers @JsonTypeInfo as a way to describe your inheritance hierarchy and give it hints on how to deserialize JSON. However, this requires that you modify your JSON and add these hints. This is explained in the documentation, here.