gpt4 book ai didi

java - BeanUtils : populate String Date formatted map field to Date property

转载 作者:行者123 更新时间:2023-11-30 05:56:15 28 4
gpt4 key购买 nike

我有这个Map<String, Object> :

Map<String, Object> map = new HashMap<String, Object>();
map.put("date", "02/11/2018@11:29:03.463+0000");

我的 bean 是:

public class MyBean {
private Date date;
// setters & getters
}

我正在尝试将我的 map 填充到 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);

关于java - BeanUtils : populate String Date formatted map field to Date property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53117885/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com