1

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 ObjectMapper? 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"
  }]
}
David Grant
  • 13,929
  • 3
  • 57
  • 63
Glide
  • 20,235
  • 26
  • 86
  • 135

1 Answers1

5

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239