将Jackson与Jersey一起使用时,JsonTypeInfo不会序列化 [英] JsonTypeInfo does not serialize when using Jackson with Jersey

查看:274
本文介绍了将Jackson与Jersey一起使用时,JsonTypeInfo不会序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JsonTypeInfo注释了JAXB类,以便可以轻松地序列化多态类.但是,由Jersey序列化时,注释不会显示.更具体地说,它在使用ObjectMapper时显示,但不作为资源的返回类型显示.我现在非常困惑,因为这似乎与Jersey => Jackson互动有关.

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.

为了调试,我使用了jersey-samples中的jsonfromjaxb示例来定位问题.我将以下内容添加到Flights类中,以使其序列化为@class.

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")

我在资源中提供了以下方法,一种仅返回JAXB对象,另一种手动使用ObjectMapper

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);
}

查询/jsonfromjaxb/flights的结果

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"}]}

查询/jsonfromjaxb/flights/object_mapper的结果

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"}]}

谢谢, 赎金

推荐答案

我认为您似乎没有使用基于Jackson的序列化(也就是说,使用ObjectMapper的序列化;大多数JSON使用低级的jackson生成器输出,包括以不同方式进行绑定的输出).如果是的话,它肯定应该看起来像您从显式使用中看到的一样.因此,似乎是更改Jersey JSON配置的问题.

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.

这篇关于将Jackson与Jersey一起使用时,JsonTypeInfo不会序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆