Using a deserializer on an array

6 views
Skip to first unread message

Bryn Hakl

unread,
Sep 27, 2024, 8:57:21 PM9/27/24
to jackson-user
I have a class with a custom data type in it that I'm serializing with annotations
```
public class Example {
    @JsonDeserialize(using = Deserializer.class)
    T exampleObject;

    //This is wrong
    @JsonDeserialize(using = Deserializer.class)
    T[] exampleArray;
}
```

I have a deserializer for a type T.
```java
public class Deserializer extends JsonDeserializer<T> {
 @Override
 public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
     //Do some processing
     return new T(processedData);
 }
}
```

```json
{
    "exampleObject" : "somedatahere",

    "exampleArray" : [
        "somedatahere2",
        "somemoredata",
        "someevenmoredata"
    ]
}
```

This works fine for exampleObject, but I also want to deserialize an array of these objects. Is there a way to tell Jackson to use my existing deserializer for each element of the array or do I have to make a whole new deserializer?

Tatu Saloranta

unread,
Sep 27, 2024, 9:00:14 PM9/27/24
to jackso...@googlegroups.com
On Fri, Sep 27, 2024 at 5:57 PM Bryn Hakl <bryn...@gmail.com> wrote:
>
> I have a class with a custom data type in it that I'm serializing with annotations
> ```
> public class Example {
> @JsonDeserialize(using = Deserializer.class)
> T exampleObject;
>
> //This is wrong
> @JsonDeserialize(using = Deserializer.class)

Should be

@JsonDeserializer(contentUsing = Deserializer.class)

to be used for Array (or List, Set, Map) elements; "using" refers to
the exact full value (Array).

> T[] exampleArray;

Hope this helps,

-+ Tatu +-

Bryn Hakl

unread,
Sep 28, 2024, 12:49:48 PM9/28/24
to jackso...@googlegroups.com
That works! Thanks!
Reply all
Reply to author
Forward
0 new messages