Friday 15 May 2015

java - Spring @RequestBody containing a list of different types (but same interface) -


Assume that I have a domain class:

  public class zoo {private list} & Lt; Animals & gt; Animals; ....   

Where an animal has an interface with different implementations (cat, dog). Suppose I would like to save a zoo item:

  @RequestMapping (value = "/ zoo", method = RequestMethod.POST) public @ResponseBody void save (@RequestBody zoo) {.. .. and I want to send a Jason - something like:  
  {animal: [[type: 'cat', armor type: '3 '}, {Type:' dog ', name:' fancy '}}   

How can I tell spring MVC to map animals for cat type when typing == 'Cat' and to map it to a dog class By type == 'dog'?

You should use Jackson Annotation and get Polymorphic Jason. Annotations go to the Animal Base Class. @ JsonTypeInfo (use = ID.name, include = es.property, property = "type") @ jasonspets ({@ JsonSubTypes.Type (value = Dog.class, name = "Dog"), @ JsonSubTypes.Type (value = Cat.class, name = "Cat")} Public Intangible Class Animal {}

No comments:

Post a Comment