简体   繁体   English

自定义JSON序列化列表 <MyClass> 与杰克逊

[英]Custom JSON serialization for List<MyClass> with Jackson

MyClass is as follows: MyClass如下:

@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. 我希望List用Jackson序列化为JSON,但是格式不符合预期。 I'm currently digging the Jackson docs but they are a bit tricky for the first read. 我目前正在研究Jackson文档,但对于初读而言有些棘手。

The JSON output is now: 现在,JSON输出为:

[ {
   "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 您需要@JsonValue批注: http : @JsonValue

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

This tells Jackson how MyClass should be treated while being serialized to JSON. 这告诉杰克逊在序列化为JSON时应如何对待MyClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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