简体   繁体   English

将Jackson与Jersey一起使用时,JsonTypeInfo不会序列化

[英]JsonTypeInfo does not serialize when using Jackson with Jersey

I annotated a JAXB class with JsonTypeInfo so that I could serialize polymorphic classes easily. 我用JsonTypeInfo注释了JAXB类,以便可以轻松地序列化多态类。 However, the annotation does not show up when serialized by Jersey. 但是,由Jersey序列化时,注释不会显示。 To be more specific, it shows up when using ObjectMapper but not as a return type from a resource. 更具体地说,它在使用ObjectMapper时显示,但不作为资源的返回类型显示。 I am very confused right now as this seems to be a problem with Jersey => Jackson interaction. 我现在非常困惑,因为这似乎与Jersey => Jackson互动有关。

To debug things, I used the jsonfromjaxb example from the jersey-samples to localize my problem. 为了调试,我使用了jersey-samples中的jsonfromjaxb示例来定位问题。 I added the following to the Flights class to have it serialize out to @class. 我将以下内容添加到Flights类中,以使其序列化为@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 我在资源中可以使用以下方法,一种仅返回JAXB对象,另一种手动使用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 查询/ 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 查询/ 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 谢谢,赎金

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). 我认为您似乎没有使用基于Jackson的序列化(也就是说,使用ObjectMapper的序列化;大多数JSON输出都使用了低级的jackson生成器,包括绑定方式有所不同的序列化)。 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. 因此,似乎是更改Jersey JSON配置的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM