我使用orika 1.5.2。当将数据从HashMap映射到bean并将String转换为java.util.Date时,我得到了异常:
java.lang.ClassCastException:java.lang.String无法强制转换为java.util.Date
DateToStringConverter也没有生效。但是当我将数据从Bean A映射到Bean B时,异常不会出现。
当我将数据从Map映射到bean时,如何将String转换为Date?
代码:
public class UserA {
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "UserA [birthday=" + birthday + "]";
}
}
public static void main(String[] args){
HashMap map = new HashMap();
map.put("birthday", "2014-04-28");
UserA ua = new UserA();
MapperFactory mapF = new DefaultMapperFactory.Builder().mapNulls(false).build();
mapF.getConverterFactory().registerConverter(new DateToStringConverter("yyyy-MM-dd"));
mapF.getMapperFacade().map(map, ua);
}
异常: Exception
答案 0 :(得分:0)
您需要对象到日期转换器,而不是DateToStringConverter
用户:
@Data
public class UserA {
private Date birthday;
}
添加转换器
public class ObjectToDateConverter extends CustomConverter<Object, Date> {
@Override
public Date convert(Object source, Type<? extends Date> destinationType, MappingContext context) {
if (source instanceof String) {
try {
return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse((String) source);
} catch (ParseException e) {
return null;
}
}
return null;
}
}
测试:
@Test
public void testMap(){
HashMap map = new HashMap();
map.put("birthday", "2018-10-14");
UserA ua = new UserA();
MapperFactory mapF = new DefaultMapperFactory.Builder().mapNulls(false).build();
mapF.getConverterFactory().registerConverter(new ObjectToDateConverter());
mapF.getMapperFacade().map(map, ua);
}