Marcus Leon
Marcus Leon

Reputation: 56709

Jersey JSON marshalling of empty lists

We have a Java List of objects which is marshalled via JSON which is created by Jersey.

The List is called "rows". When there is data we have:

{"records":"1","page":"1","total":"1","rows":[{"id":"692334","cell":["ECS","D","201009","","0","ABCD","11","11","","201009"]}]}

When there is no data we have:

{"page":0,"records":0,"total":0}

How can we make Jersey include the rows field even if the List has a size of 0? What we want is:

{"page":0,"records":0,"total":0,"rows":[]}

Note that we are already using a JAXB ContextResolver to ensure the JSON is correct for a single row. Not sure if we can configure this resolver to solve our problem.

Upvotes: 4

Views: 3853

Answers (3)

Whome
Whome

Reputation: 10400

I managed to solve JSON array "bug" in Jersey json library. Secret ingredient is previusly mentioned 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

Upvotes: 0

Matthias B
Matthias B

Reputation: 5577

Maybe this helps you: http://jersey.java.net/nonav/documentation/latest/json.html#d4e903

seems that some array problems can be solved by using something like this:

JSONConfiguration.mapped().arrays("yourArrayName").build()

At least it solves the issue, when the list contains only 1 item it's also formated as an JSON array.

Upvotes: 0

StaxMan
StaxMan

Reputation: 116620

Use Jackson JAX-RS provider instead of alternatives (badgerfish/jettison), which does not do XML-to-JSON conversion. Missing array is most likely due to this conversion. There are multiple ways to configure this (jersey mailing list should have a few), and latest versions may expose it directly via Jersey API.

Upvotes: 5

Related Questions