Marshalling an empty collection to json using jersey

吃可爱长大的小学妹 提交于 2019-12-11 16:11:45

问题


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.


回答1:


Are you serializing an empty list, or are you serializing an un-instantiated null object?

ie. I would expect:

private List<Foo> foos; - would serialize to 'stuff: [null]'

and I would also expect:

private List<Foo> foos = new ArrayList<Foo>(); - we serialize to 'stuff: []'

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..




回答2:


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:

"stuff" : [ { ... }, { ... } ]

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




回答3:


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

  • json array for zero or single-element Java lists
  • primitive integer or boolean fields without quotation chars


来源:https://stackoverflow.com/questions/8210011/marshalling-an-empty-collection-to-json-using-jersey

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!