简体   繁体   中英

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 [].

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM