Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) not working when Response is returned

I'm writing a REST service using Jersey. I have an abstract class Promotion that has an annotation:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)

Thanks to that, when I return a list of objects:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("promotions/")
public List<Promotion> getClosestPromotions() {
List<Promotion> promotions = getPromotions(); //here I get some objects

return promotions;
}

I get a Json string with a "@class" field for every object in that list. But the problem is that if I return a Response:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("promotions/")
public Response getClosestPromotions() {
List<Promotion> promotions = getPromotions(); //here I get some objects

return Response.ok().entity(promotions).build();
}

I'm getting almost the same list, but without additional "@class" field. Why is that and what can I do to get a list with "@class" field returning a list in Response? And by the way, surprisingly, it works when I return a Response with one Promotion object only given as an entity and I get that "@class" field.

like image 567
krajol Avatar asked Dec 10 '12 21:12

krajol


2 Answers

Maybe you would want to try:

GenericEntity<Collection<Promotion>> genericEntity = 
           new GenericEntity<Collection<Promotion>>(promotions){};
return Response.ok().entity(genericEntity).build();
like image 88
JChrist Avatar answered Nov 16 '22 00:11

JChrist


Try adding the sub types annotation, here is an example that I am using. This may solve your problem by specifying all the operable sub types. Sorry didn't test your exact example.

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonSubTypes({
    @JsonSubTypes.Type(value=MetricCollection.class),
    @JsonSubTypes.Type(value=Column.class),
    @JsonSubTypes.Type(value=IntegerColumn.class),
    @JsonSubTypes.Type(value=DoubleColumn.class),
    @JsonSubTypes.Type(value=StringColumn.class)
})
public interface IMetricCollection<T extends IMetric> {
...
}
like image 37
Chris Hinshaw Avatar answered Nov 16 '22 02:11

Chris Hinshaw