BeanUtils:将字符串日期格式的映射字段填充为日期 属性
BeanUtils: populate String Date formatted map field to Date property
我有这个Map<String, Object>
:
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "02/11/2018@11:29:03.463+0000");
我的豆子是:
public class MyBean {
private Date date;
// setters & getters
}
我正在尝试将我的地图填充到 bean:
MyBean bean = new MyBean();
BeanUtilsBean.getInstance().populate(bean, map);
我收到此错误消息:
ConversionException: DateConverter does not support default String to 'Date' conversion.
重要提示:我无法更改字符串格式。
我该如何解决?
您必须注册转换器:
class MyDateConverter implements Converter {
private final DateFormat format = new SimpleDateFormat("dd/MM/yyyy@HH:mm:ss.SSSZ");
public Object convert(Class type, Object value) {
if(value == null) {
return null;
} else { // parse your date format with date formatter
try {
return format.parse((String) value);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
}
并像这样使用它:
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
convertUtilsBean.register(new MyDateConverter(), Date.class);
BeanUtilsBean beanUtilsBean =
new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
MyBean bean = new MyBean();
beanUtilsBean.populate(bean, map);
您可以创建 DateTimeConverter
的实例并传入您的自定义模式。这是一个例子:
DateTimeConverter dateConverter = new DateConverter(null);
dateConverter.setPatterns(new String[] {"dd/MM/yyyy@HH:mm:ss.SSSZ"});
ConvertUtils.register(dateConverter, Date.class);
我有这个Map<String, Object>
:
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "02/11/2018@11:29:03.463+0000");
我的豆子是:
public class MyBean {
private Date date;
// setters & getters
}
我正在尝试将我的地图填充到 bean:
MyBean bean = new MyBean();
BeanUtilsBean.getInstance().populate(bean, map);
我收到此错误消息:
ConversionException: DateConverter does not support default String to 'Date' conversion.
重要提示:我无法更改字符串格式。
我该如何解决?
您必须注册转换器:
class MyDateConverter implements Converter {
private final DateFormat format = new SimpleDateFormat("dd/MM/yyyy@HH:mm:ss.SSSZ");
public Object convert(Class type, Object value) {
if(value == null) {
return null;
} else { // parse your date format with date formatter
try {
return format.parse((String) value);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
}
并像这样使用它:
ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
convertUtilsBean.register(new MyDateConverter(), Date.class);
BeanUtilsBean beanUtilsBean =
new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
MyBean bean = new MyBean();
beanUtilsBean.populate(bean, map);
您可以创建 DateTimeConverter
的实例并传入您的自定义模式。这是一个例子:
DateTimeConverter dateConverter = new DateConverter(null);
dateConverter.setPatterns(new String[] {"dd/MM/yyyy@HH:mm:ss.SSSZ"});
ConvertUtils.register(dateConverter, Date.class);