views:

83

answers:

1

How do I get Jackson to serialize my Joda DateTime object according to a simple pattern (like "dd-MM-yyyy"?

I've tried:

@JsonSerialize(using=DateTimeSerializer.class)
private final DateTime date;

I've tried:

ObjectMapper mapper = new ObjectMapper()
    .getSerializationConfig()
    .setDateFormat(df);

Thanks!

+2  A: 

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}
Rusty Kuntz