Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

json - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...