Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @ReponseBody @RequestBody with abstract class

Suppose I have three classes.

public abstract class Animal {}  public class Cat extends Animal {}  public class Dog extends Animal {} 

Can I do something like this?

Input: a JSON which it is Dog or Cat

Output: a dog/cat depends on input object type

I don't understand why the following code doesn't work. Or should I use two separate methods to handle new dog and cat?

@RequestMapping(value = "/animal", method = RequestMethod.POST, produces = "application/json; charset=utf-8") private @ResponseBody <T extends Animal>T insertAnimal(@RequestBody T animal) {     return animal; } 

Error message:

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Type variable 'T' can not be resolved

like image 704
tl1181231 Avatar asked Nov 27 '14 12:11

tl1181231


People also ask

Can I inject an abstract class in Spring?

Third, as Spring doesn't support constructor injection in an abstract class, we should generally let the concrete subclasses provide the constructor arguments. This means that we need to rely on constructor injection in concrete subclasses.

Can we use @RequestBody with get in Spring boot?

spring v5. 3.6 supports request body with GET.

Is @RequestBody required with @RestController?

If you don't add @RequestBody it will insert null values (should use), no need to use @ResponseBody since it's part of @RestController.

What does @RequestBody do in Spring?

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object. Spring automatically deserializes the JSON into a Java type, assuming an appropriate one is specified.


Video Answer


1 Answers

ref link

I just found the answer myself and here is the reference link.

What I have done is added some code above the abstract class

import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.*;  @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({     @JsonSubTypes.Type(value = Cat.class, name = "cat"),     @JsonSubTypes.Type(value = Dog.class, name = "dog") }) public abstract class Animal{} 

Then in the json input in HTML,

var inputjson = {     "type":"cat",     //blablabla }; 

After submitting the json and finally in the controller,

@RequestMapping(value = "/animal", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes=MediaType.APPLICATION_JSON_VALUE) public @ResponseBody insertanimal(@RequestBody Animal tmp) {     return tmp; } 

In this case variable tmp is automatically converted to a Dog or Cat object, depending on json input.

like image 88
tl1181231 Avatar answered Sep 21 '22 17:09

tl1181231