用杰克逊序列化日期列表

serialize list of dates with Jackson

我正在尝试序列化一个包含日期列表的对象,我想序列化为特定格式 (yyyy-MM-dd) 的 JSON 日期列表(字符串)。

private List<Date> executionDates;

会变成这样:

"executionDates": [
  "2016-07-22",
  "2016-07-23",
  "2016-07-24"
]

可以用注解来做吗?

提前致谢。

尝试这样的事情:

对于序列化:

@Component
public class JsonDateSerializer extends JsonSerializer<Date>
{
    // ISO 8601
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException
    {
        String formattedDate = dateFormat.format(date);
        gen.writeString(formattedDate);
    }
}

我找到了解决方案。我不得不在这样的注释中使用 属性 contentUsing 而不是 using

@JsonSerialize(contentUsing = JsonDateSerializer.class)

contentUsing 属性 用于 collections。来自 class 文档:

Serializer class to use for serializing contents (elements of a Collection/array, values of Maps) of annotated property. Can only be used on properties (methods, fields, constructors), and not value classes themselves (as they are typically generic).