json - Spring @ReponseBody @RequestBody with abstract class -
suppose have 3 classes.
public abstract class animal {} public class cat extends animal {} public class dog extends animal {}
can this?
input: json dog or cat
output: dog/cat depends on input object type
i dont understand why following code doesnt work. or should use 2 separate methods handle new dog , 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; }
update: sry forget include error message
http status 500 - request processing failed; nested exception java.lang.illegalargumentexception: type variable 't' can not resolved
i found answer myself , here reference link.
what have done added code above 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 json input in html,
var inputjson = { "type":"cat", //blablabla };
after submitting json , in 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 case variable tmp automatically converted dog
or cat
object, depending on json input.
Comments
Post a Comment