Pablo
Pablo

Reputation: 201

Spring 3 with ResponseBody ignoring @JsonTypeInfo

I can't make spring return a serialization of my object with the additional property defining the class.

My classes are:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.PROPERTY, property="ObjectType")
@JsonSubTypes({
    @JsonSubTypes.Type(value=LiteStudy.class, name="LiteStudy")
})
public class Entity {
...
}


@JsonTypeName("LiteStudy")
@JsonSubTypes({
        @JsonSubTypes.Type(value=Study.class, name="Study")
})
public class LiteStudy extends Entity {
...
}


@JsonTypeName("Study")
public class Study extends LiteStudy{
...
}

In my unit test, an Study instance is serialised properly, having the extra property for the class:

{"ObjectType":"Study",
...
}

Using for this a simple:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(studyJSON,study.getClass());

However, in my Spring Rest webservice module the study is serialized without the "ObjectType" property.

The controller looks like this (simplified):

@ResponseBody
public RestResponse<Study> getStudyById(@PathVariable("studyIdentifier")    String studyIdentifier) throws DAOException {

    return getStudyRestResponse(studyIdentifier);
}

EDIT: Adding RestResponse (Simplified)

public class RestResponse<Content> {

private Content content;
private String message;
private Exception err;

public Content getContent() {
    return content;
}

public void setContent(Content content) {
    this.content = content;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public Exception getErr() {
    return err;
}

public void setErr(Exception err) {
    this.err = err;
}

Any idea why spring seems to be ignoring the @JsonType annotations?

Upvotes: 1

Views: 1757

Answers (1)

Nikolay Rusev
Nikolay Rusev

Reputation: 4230

Try to return only the object you need, do not wrap it in generic wrapper class. Your problem is related to Java Type erasure. See more info here

@ResponseBody
    public @ResponseBody Study getStudyById(@PathVariable("studyIdentifier")    String studyIdentifier) throws DAOException {

        return studyIdentifier;
    }

Upvotes: 2

Related Questions