在BeanUtils注册自定义类型转换规则转换bean map
使用org.apache.commons.beanutils.BeanUtils.describe可以将bean转换为Map<String,String>,但是某些特殊类型在通过BeanUtils.populate转换时会报错,例如JAVA8的LocalDateTime
org.apache.commons.beanutils.ConversionException: Default conversion to java.time.LocalDateTime failed.
解决
注册转换器
// 覆盖默认的String类型转换器,将LocalDateTime类型属性转换为时间戳文本
BeanUtilsBean.getInstance().getConvertUtils().register(new AbstractConverter() {
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
if (String.class.equals(type) || Object.class.equals(type)) {
return type.cast(value.toString());
}
throw conversionException(type, value);
}
@Override
protected Class<?> getDefaultType() {
return String.class;
}
@Override
protected String convertToString(Object value) throws Throwable {
if (value instanceof LocalDateTime) {
return String.valueOf(((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
} else {
return super.convertToString(value);
}
}
}, String.class);
// 注册LocalDateTime类型转换器,将时间戳文本转换为LocalDateTime
BeanUtilsBean.getInstance().getConvertUtils().register(new Converter() {
@Override
public <T> T convert(Class<T> type, Object value) {
if (value == null) {
return null;
}
return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf((String) value)), ZoneId.systemDefault());
}
}, LocalDateTime.class);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
2020-04-11 spring 启动时自动运行
2020-04-11 spring cloud oauth2授权服务 默认tokenService配置源码
2020-04-11 spring cloud 搭建oauth2授权服务 使用redis存储令牌
2020-04-11 spring cloud oauth2授权服务 clientDetails配置源码
2020-04-11 spring 验证框架
2020-04-11 IDEA 插件整理
2020-04-11 spring security笔记 默认登陆页面源码