Deserializing objects that conform to Collection API

19 views
Skip to first unread message

Mantas Gridinas

unread,
Dec 28, 2021, 7:30:51 AM12/28/21
to jackson-user
I've come about to a bit of a pickle. Suppose I have the following structure:

class CollectionWrapper<T> implements Collection<T> {
    private int count;
    private Collection<T> items;
    
    // getters setters omitted for brevity
    // Collection<T> methods delegated to items field
    // int size() method returns items.size()
}

Basically the structures I'm trying to work with are wrappers for arrays that contain total item count, but not "next page", or similar fields. As of right now, Jackson treats them as if they start with `JsonToken.START_ARRAY` (because it implements the Collection<T> interface) when in reality they're object wrappers. How do I configure jackson (preferably via JsonMapper.Builder) that this particular class should be deserialized as object, rather than an array?

Cheers!

// Mantas

Tatu Saloranta

unread,
Dec 28, 2021, 2:35:03 PM12/28/21
to jackso...@googlegroups.com
Correct: Jackson has no knowledge that you have a "special" kind of
Collection there.

I think you can use

@JsonFormat(shape = JsonFormat.Shape.OBJECT)

on your wrapper type to force it to be handled as if POJO, however.
So add that as class annotation for class declaration. That works for
serialization,
for deserialization you will need to use @JsonCreator and a specific
constructor or something.

Alternatively it's also possible to use @JsonValue to return "wrapper
wrapper" type; something that
will be serialized in place of wrapper itself (and does not implement
Collection). That would also
allow whatever serialization you want.

-+ Tatu +-

>
> // Mantas
>
> --
> 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 view this discussion on the web visit https://groups.google.com/d/msgid/jackson-user/ff942dc9-b537-4dd1-a86e-5ce2d8094c8dn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages