JsonTypeInfo does not serialize when using Jackson with Jersey

半世苍凉 提交于 2019-12-11 02:58:55

问题


I annotated a JAXB class with JsonTypeInfo so that I could serialize polymorphic classes easily. However, the annotation does not show up when serialized by Jersey. To be more specific, it shows up when using ObjectMapper but not as a return type from a resource. I am very confused right now as this seems to be a problem with Jersey => Jackson interaction.

To debug things, I used the jsonfromjaxb example from the jersey-samples to localize my problem. I added the following to the Flights class to have it serialize out to @class.

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")

I have the following methods available in the resource, one which just returns the JAXB object and one which manually uses ObjectMapper

@GET
@Produces({"application/json"})
public synchronized Flights getFlightList() {
    return myFlights;
}

@GET
@Path("/object_mapper")
@Produces({"application/json"})
public synchronized String getFlights() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(myFlights);
}

The result of querying /jsonfromjaxb/flights

{"flight":[{"flightId":"OK123","company":"Czech Airlines","number":123,"aircraft":"B737"},{"flightId":"OK124","company":"Czech Airlines","number":124,"aircraft":"AB115"}]}

The result of querying /jsonfromjaxb/flights/object_mapper

{"@class":"com.sun.jersey.samples.jsonfromjaxb.jaxb.Flights","flight":[{"number":123,"company":"Czech Airlines","aircraft":"B737","flightId":"OK123"},{"number":124,"company":"Czech Airlines","aircraft":"AB115","flightId":"OK124"}]}

Thanks, Ransom


回答1:


I think it looks like you aren't using Jackson-based serialization (that is, one that uses ObjectMapper; low-level jackson generator is used for most JSON output, including ones where binding is done differently). If you were, it definitely should look like what you see from explicit use. So it seems to be matter of changing Jersey JSON configuration.



来源:https://stackoverflow.com/questions/4899397/jsontypeinfo-does-not-serialize-when-using-jackson-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!