在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);

posted on   路过君  阅读(476)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 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笔记 默认登陆页面源码

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示