栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

杰克逊自定义日期序列化器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

杰克逊自定义日期序列化器

如果您不能使用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);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413713.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号