使用 jersey 将空集合编组为 json
我在使用 jersey 和基于 jaxb 的 json 支持将空对象集合编组为 json 时遇到一个奇怪的问题。我的对象看起来像
...
@XmlWrapper(name = "stuff") @XmlElement(name = "s")
private List<Foo> foos;
...
将其编组到 json 会产生预期的结果,
... stuff: [{ "s": ... }, { "s": ... }] ...
除非列表为空。我本来希望看到
... stuff: [] ...
,但我
... stuff: [null] ...
却看到了。 知道出了什么问题吗? 问题似乎与 @XmlElementWrapper
注释有关,删除它后我没有得到 stuff
属性的输出。
I have a strange issue marshalling an empty object collection to json using jersey with the jaxb based json support. My object looks like
...
@XmlWrapper(name = "stuff") @XmlElement(name = "s")
private List<Foo> foos;
...
Marshaling this to json produces the expected results
... stuff: [{ "s": ... }, { "s": ... }] ...
except when the list is empty. I would expect to see
... stuff: [] ...
but I see
... stuff: [null] ...
instead. Any idea what's wrong? The problem seems to be related to the @XmlElementWrapper
annotation, removing it I don't get the the stuff
property in the output at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是序列化一个空列表,还是序列化一个未实例化的空对象?
IE。我期望:
并且我也期望:
如果情况并非如此,您始终可以将 Jackson(这是与 Jersey 捆绑在一起的默认 JSON 序列化器)定向到 省略将 bean 属性写入 null 值。。
Are you serializing an empty list, or are you serializing an un-instantiated null object?
ie. I would expect:
and I would also expect:
If that isn't the case, you can always direct Jackson (which is the default JSON serializer bundled with Jersey) to omit the writing of bean properties as null value..
我建议使用基于 Jackson 的 POJO 映射。我不确定为什么你想要中间的“s”在那里,但 POJO 会产生(并消耗)更简单的结构:
为此,你不需要 POJO 映射的注释; JAXB 注释仅在 XML 处理时需要,因为 XML 没有区分数组和对象的自然机制(与 JSON 不同)。
I would suggest using POJO mapping based on Jackson. I am not sure why you want that intermediate "s" in there, but POJO would produce (and consume) simpler structure:
For that you need no annotations with POJO mapping; JAXB annotations are only needed for XML processing, since XML has no natural mechanism to distinguish arrays from objects (unlike JSON).
我设法解决了 Jersey json 库中的 JSON 数组和原始字段“bug”。秘密成分是 JSONConfiguration 和 ContextResolver 魔法。请参阅我的下一篇文章,它有一个完整的代码示例,自定义的 ContextResolver 和其余的 Application 类乍一看可能有点模糊逻辑。
如何使用 Jersey REST 序列化 Java 原语
I managed to solve JSON array and primitive field "bug" in Jersey json library. Secret ingredient is JSONConfiguration and ContextResolver magic. See my following post it has a full code example, customized ContextResolver and rest Application class might be somewhat fuzzy logic in first look.
How to serialize Java primitives using Jersey REST