gyorgyabraham
gyorgyabraham

Reputation: 2608

Custom JSON serialization for List<MyClass> with Jackson

MyClass is as follows:

@Getter
class MyClass
{
    private final DateTime start;
    private final DateTime end;
}

I want a List to serialize into JSON with Jackson but the format is not as expected. I'm currently digging the Jackson docs but they are a bit tricky for the first read.

The JSON output is now:

[ {
   "end" : "2012-02-16T13:59:59.000+01:00",
   "start" : "2012-02-16T13:35:42.000+01:00"
 }, {
   "end" : "2012-02-16T16:59:59.000+01:00",
   "start" : "2012-02-16T16:00:00.000+01:00"
 } ]

But I want it to be:

[ [ "2012-02-16T13:59:59.000+01:00", "2012-02-16T13:35:42.000+01:00"],
[ "2012-02-16T16:59:59.000+01:00", "2012-02-16T16:00:00.000+01:00" ] ]

So don't print member names and replace inner {} with [].

Upvotes: 1

Views: 2492

Answers (1)

Eser Aygün
Eser Aygün

Reputation: 8004

@JsonValue annotation is what you need: http://jackson.codehaus.org/1.0.1/javadoc/org/codehaus/jackson/annotate/JsonValue.html

class MyClass {
    ...
    @JsonValue
    private DateTime[] toValue() {
        return new DateTime[] {start, end};
    }
}

This tells Jackson how MyClass should be treated while being serialized to JSON.

Upvotes: 7

Related Questions