Let's say that I have a domain class :
public class Zoo{ private List<Animal> animals; ....
where an Animal is an interface with different implementations (Cat,Dog). Let's say that I want to be able to save a Zoo object :
@RequestMapping(value = "/zoo", method = RequestMethod.POST) public @ResponseBody void save(@RequestBody Zoo zoo) { ....
and I want to send a json - something like :
{ animals:[ {type:'Cat', whiskers-length:'3'}, {type:'Dog', name:'Fancy'} ] }
How can I tell spring MVC to map animal to Cat type when type=='Cat' and to map it to a Dog class when type=='Dog'?
@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.
Thanks. spring v5. 3.6 supports request body with GET.
The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the HTTP response automatically.
With Spring's latest version, if you use @RequestBody annotation, it makes client to send body all the time without making it optional.
You should use the Jackson annotations @JsonTypeInfo
and @JsonSubTypes
to achieve polymorphic json. The annotations go on the Animal
base class.
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({@JsonSubTypes.Type(value = Dog.class, name = "Dog"), @JsonSubTypes.Type(value = Cat.class, name = "Cat")}) public abstract class Animal { }
There is a simpler annotation out now:
@JsonRootName("dog") public class Dog extends Animal {...}
The reference to the annotation can be found on fasterxml.github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With