Glide Glide - 1 year ago 89
JSON Question

Jackson deserialize JSON that intermittently has an array

I'm retrieving JSON back from a web service. Sometimes the property in the JSON would return as an object, and other times it's an array of the object. How can I write the Java class that I'm deserializing into to deserialize properly this property with Jackson's

? Can I do with the ObjectMapper to help with this?

JSON with object:

"results": {
"account": {
     "expiration": "2012-11-16"

JSON with collection

"results": {
  "account": [{
    "expiration": "2012-11-16"

Answer Source

You need to mark the property as a Java array or Collection, and enable feature ACCEPT_SINGLE_VALUE_AS_ARRAY:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature. ACCEPT_SINGLE_VALUE_AS_ARRAY);
ResultOb ob = mapper.readValue(jsonInput, ResultOb.class);

and if a single JSON Object is encountered, it gets treated like it was a single-element JSON Array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download