【问题标题】:Restlet/Jackson JSON wrapper for ArrayList<Profile>ArrayList<Profile> 的 Restlet/Jackson JSON 包装器
【发布时间】:2012-01-16 15:56:26
【问题描述】:

我正在将 Restlet 库用于 WS 服务器,并且由于一些问题,我最近从 XStream/Jettison 切换到 Jackson 作为 JSON 序列化器/反序列化器。

第一个缺点是我的 ArrayList(以前是带有 Jettison 的 Vector)它在序列化时不包装 Profiles 列表,而不是 JSON 而不是 "Profile:[{firstProfile}, {secondProfile}]"看起来像:[{firstProfile}, {secondProfile}]

我可以在客户端手动告诉哪个是正确映射时克服这个问题,但我更喜欢使用 KVC 方法。

我环顾四周,似乎这是一个已知问题:http://wiki.fasterxml.com/JacksonPolymorphicDeserialization (5.1 Missing type information on Serialization) 它建议:

  • 使用数组而不是列表
  • 子类列表,使用类 MyPojoList extends ArrayList { }
  • 强制使用特定的根类型

最简单的方法应该是返回一个“Profile[] profile”数组,但它似乎不起作用,在尝试我重新检查过的其他解决方案之前,你似乎可以使用 @XmlRootElement(name = "Profile ") 来包装 JSON 根元素:http://jira.codehaus.org/browse/JACKSON-163?focusedCommentId=213588&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-213588

所以要在 Jackson 中使用 JAXB 注释,您需要配置 objectMapper:http://wiki.fasterxml.com/JacksonJAXBAnnotations

但在 restlet 中,您需要重写 createObjectMapper 以传递自定义转换器(请参阅:http://restlet-discuss.1400322.n2.nabble.com/Set-custom-objectMapper-to-Jackson-Extension-td6287812.htmlhttp://restlet-discuss.1400322.n2.nabble.com/Jackson-Mix-in-Annotations-td6211060.html#a6231831

这就是我现在正在尝试的!问题是否有更直接的方法来实现这一点??

谢谢!!

【问题讨论】:

  • 我很高兴杰克逊没有使用那个糟糕的 Foo:{key,value} 符号..
  • 似乎在这个例子中它正在工作:stackoverflow.com/questions/3954265/… 唯一的区别是我没有使用接口并且restlet负责序列化(restlet jse 2.1rc2)
  • 实际上我直接返回一个 ArrayList 而不是一个带有 ArrayList 的包装类
  • 我也尝试过从杰克逊文档中获取“子类列表”,但似乎我做错了什么,如果您返回 Restlet,解决方案是将 ArrayList 包装在一个类中该实例的所有元素都将使用 ArrayList 实例的名称进行包装。这样客户端就可以对json进行KVC

标签: json serialization jaxb jackson restlet


【解决方案1】:

对我来说,解决方案是用以下方式注释 Profile 类:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
public class Profile extends Element implements Serializable {

现在 json 看起来像:

{"Profile":{ ... }}

并且返回类型是一个子类列表:

public class ProfileList extends ArrayList<Profile>
{}

http://wiki.fasterxml.com/JacksonPolymorphicDeserialization5.1

【讨论】:

    【解决方案2】:

    我认为你想要的并不是真正可用的,因为 JAX-B 似乎对如何处理列表有一些规则。见this converstation on the RESTeasy mailing list

    【讨论】:

    • 感谢您的回复,我没有尝试返回 GenericEntity> x = new GenericEntity>();将 ArrayList 包装在一个类中并返回该实例的解决方案对我来说很好,我想知道我是否可以用更优雅的方式避免这种情况..但这并不重要:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多