4

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429

3 Answers3

5

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
0

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
Community
  • 1
  • 1
Whome
  • 10,181
  • 6
  • 53
  • 65
0

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.

Matthias B
  • 5,523
  • 3
  • 45
  • 47