How to conditionally convert JSON to an array during deserialization

851 views
Skip to first unread message

Tristan Burch

unread,
Sep 21, 2015, 3:22:51 PM9/21/15
to jackson-user
Hi,

I've been trying to figure this out, but haven't had any luck yet, so I thought I'd post here for some help...

I have the following JSON, where the 'response' field can either be an object or a collection of those objects:
{
    "success": false,
    "error": {
        "code": "invalid_location",
        "description": "The requested location was not found in the database."
    },
    "response": [ ]
}

I'd like to map the JSON to the following POJO:
public abstract class Response<T> {
  private boolean success;
  private Error error;
  private Collection<T> response;
}

Is there a way to write a conditional deserializer that will check to see if 'response' is an object and if so, convert it to a collection of those objects? I've looked at @JsonDeserialize and the converters, but couldn't get it to do what I wanted.

Thanks!
-Tristan

Tatu Saloranta

unread,
Sep 21, 2015, 3:35:52 PM9/21/15
to jackson-user
I think what you are looking for would be

 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY

which will allow general mapping of a single Object into List/array of Objects (with matching content type).

Or, with Jackson 2.6, you can also define it on per-property basis, like:

class Response<T> {
   ...
   @JsonFormat(with=JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
   private Collection<T> response
}

which may be nice if you only want to allow for specific properties.

-+ Tatu +-


--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tristan Burch

unread,
Sep 21, 2015, 4:23:01 PM9/21/15
to jackson-user
Thanks Tatu!
Reply all
Reply to author
Forward
0 new messages