如何配置ModelMapper实现LocalDateTime到long的类型转换?
解决ModelMapper中LocalDateTime转long的映射异常问题
问题原因
配置的自定义属性映射未覆盖ModelMapper默认映射逻辑,框架仍尝试用内置的NumberConverter将LocalDateTime的字符串形式转为long,触发NumberFormatException。
解决方案
方案1:跳过默认映射,强制使用自定义逻辑
在添加自定义映射前,先跳过time属性的默认映射规则:
ModelMapper mapper = new ModelMapper(); mapper.getConfiguration() .setMatchingStrategy(MatchingStrategies.STRICT); mapper.typeMap(Source.class, Destination.class) .addMappings(map -> { // 跳过默认的time属性映射 map.skip(Destination::setTime); // 应用自定义转换逻辑 map.map(src -> toMillis(src.getTime()), Destination::setTime); }); private static long toMillis(LocalDateTime dt) { if (dt == null) { return 0; } ZonedDateTime zdt = ZonedDateTime.of(dt, ZoneId.systemDefault()); return zdt.toInstant().toEpochMilli(); }
方案2:注册全局转换器
若需在全局范围内统一处理LocalDateTime到long的转换,可注册全局转换器:
ModelMapper mapper = new ModelMapper(); mapper.getConfiguration() .setMatchingStrategy(MatchingStrategies.STRICT); // 定义并注册全局转换器 Converter<LocalDateTime, Long> localDateTimeToLongConverter = context -> { LocalDateTime dt = context.getSource(); if (dt == null) { return 0L; } ZonedDateTime zdt = ZonedDateTime.of(dt, ZoneId.systemDefault()); return zdt.toInstant().toEpochMilli(); }; mapper.addConverter(localDateTimeToLongConverter); // 无需单独配置typeMap,框架会自动使用全局转换器 Destination dst = mapper.map(src, Destination.class);
场景说明
- 方案1适用于仅在特定类对之间需要该转换逻辑的场景;
- 方案2适用于整个应用中需要统一处理
LocalDateTime转long的场景。
内容的提问来源于stack exchange,提问作者Maurice Perry
相关产品推荐
相关产品推荐

