如果您不能使用Jackson
2中的@JsonFormat,建议您引入自己的自定义注释,其中将包含格式字段。然后,您的Serailizer应该实现该
ContextualSerializer接口以获取对注释值的访问。
这是杰克逊1.9.X的示例:
public class JacksonDateFormat { @Retention(RetentionPolicy.RUNTIME) public static @interface MyJsonFormat { String value(); } public static class Bean { @MyJsonFormat("dd.MM.yyyy") @JsonSerialize(using = MyDateSerializer.class) public final Date date1; @MyJsonFormat("yyyy-MM-dd") @JsonSerialize(using = MyDateSerializer.class) public final Date date2; public Bean(final Date date1, final Date date2) { this.date1 = date1; this.date2 = date2; } } public static class MyDateSerializer extends JsonSerializer<Date> implements ContextualSerializer { private final String format; private MyDateSerializer(final String format) {this.format = format;} public MyDateSerializer() {this.format = null;} @Override public void serialize( final Date value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { jgen.writeString(new SimpleDateFormat(format).format(value)); } @Override public JsonSerializer createContextual( final SerializationConfig serializationConfig, final BeanProperty beanProperty) throws JsonMappingException { final AnnotatedElement annotated = beanProperty.getMember().getAnnotated(); return new MyDateSerializer(annotated.getAnnotation(MyJsonFormat.class).value()); } } public static void main(String[] args) throws IOException { final ObjectMapper mapper = new ObjectMapper(); final Bean value = new Bean(new Date(), new Date()); System.out.println(mapper .writerWithDefaultPrettyPrinter() .writevalueAsString(value)); }}输出:
{ "date1" : "02.12.2014", "date2" : "2014-12-02"}如果您可以访问,
ObjectMapper则可以为所有
Date类型注册自定义序列化程序,因此您需要更长的时间放置
@JsonSerialize注释。
这是一个例子:
final ObjectMapper mapper = new ObjectMapper();final SimpleModule module = new SimpleModule("", Version.unknownVersion());module.addSerializer(Date.class, new MyDateSerializer(null));mapper.registerModule(module);


