如何让泽西/杰克逊序列化空列表;单个元素列表作为数组 [英] How to make Jersey/Jackson serialize empty list; single element list as an array
问题描述
使用Jersey和Jackson创建REST接口,当包含0或1个元素时,如何将List字段序列化为列表。例如:
Using Jersey and Jackson to create a REST interface, how do I get List fields to be serialized as a list when there are 0 or 1 elements in them. For example:
@XmlRootElement(name="foo")
public class Foo {
@XmlElement
public List<Bar> getBars() {
return this.bars;
}
}
@Path("foo")
public FooResource {
@GET
public Foo getFoo() {
return theFoo;
}
}
当柱子没有元素时,结果序列化为 null
当它包含单个元素时,它将序列化为该元素,而不是包含单个元素的数组。有没有办法让这些总是序列化为一个数组?
When bars has no elements, the result serializes as null
and when it contains a single element, it serializes as that element, not an array containing a single element. Is there a way to get these to always serialize as an array?
作为参考,我使用Jersey 1.10和Jackson 1.9.2。
For reference, I'm using Jersey 1.10 and Jackson 1.9.2.
推荐答案
我很确定你实际上并没有使用Jackson(JSON序列化的POJO变体),因为Jackson不会转换单元素数组或列出其他任何东西。所以你可能正在使用一种传统的输出方法(如jettison);这意味着,如果您将系统配置为使用POJO映射,它应该可以工作。
I am pretty sure that you are not actually using Jackson ("POJO" variant of JSON serialization), since Jackson would not convert single-element arrays or lists to anything else. So you are probably using one of legacy output methods (like jettison); meaning that if you configure system to use POJO mapping it should just work.
这篇关于如何让泽西/杰克逊序列化空列表;单个元素列表作为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!