MOXy - Force Single Element Arrays to be Objects

278 views Asked by At

We have a Jersey 1.18 jax-rs service that used to use the jersey-json package for JSON support. We're attempting to migrate to use MOXy, but not break our JSON interface. Unfortunately jersey-json marshals single element lists as objects and multi-element lists as arrays. MOXy by default marshals lists of all lengths as an array. We understand that the way MOXy is marshalling is easier for clients to consume, however we already have many clients using our interface, and it would break the interface to start marshalling single element lists as an array. Is there a way for MOXy to be configured to marshal single element lists as objects instead of arrays?

The way that jersey-json marshals single-element lists:

"user": {
    "name": "Fred Durst",
    "phone": "555-222-1111"
}

The way MOXy marshals single-element lists:

"user": [
    {
        "name": "Fred Durst",
        "phone": "555-222-1111"
    }
]

We want to configure MOXy to produce the former serialization for single-element lists. Is that possible? We're using v2.5.2 of MOXy.

1

There are 1 answers

0
Samuel On BEST ANSWER

Looks like this is possible by setting the following property:

MarshallerProperties.JSON_REDUCE_ANY_ARRAYS

to true. If you're using the MOXyJsonProvider you must subclass and implement preWriteTo() to gain access to the Marshaller object and set the property above.

EDIT JSON_REDUCE_ANY_ARRAYS does not work. See this bug.