http request to javabean
所属分类 java
浏览量 853
http request to javabean
public class User {
private String name;
private int age=-1;
private Date birth;
private Double weight;
private Double height;
org.apache.commons.beanutils.BeanUtils
request ==> Map ==> User
static {
DateConverter convert = new DateConverter();
String[] patterns = { "yyyyMMdd", "yyyy-MM-dd" };
convert.setPatterns(patterns);
ConvertUtils.register(convert, Date.class);
}
public static T toBean(Map map, Class beanClass) throws Exception{
if(map==null || beanClass==null) {
return null;
}
T bean = beanClass.newInstance();
BeanUtils.copyProperties(bean, map);
return bean;
}
完整代码
https://gitee.com/dyyx/hellocode/blob/master/demo/mydemo/src/main/java/dyyx/Map2BeanUtil.java
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import com.alibaba.fastjson.JSON;
public class Map2BeanUtil {
static {
DateConverter convert = new DateConverter();
String[] patterns = { "yyyyMMdd", "yyyy-MM-dd" };
convert.setPatterns(patterns);
ConvertUtils.register(convert, Date.class);
}
public static T toBean(Map map, Class beanClass) throws Exception{
if(map==null || beanClass==null) {
return null;
}
T bean = beanClass.newInstance();
BeanUtils.copyProperties(bean, map);
return bean;
}
public static void main(String[] args) throws Exception{
Map map = new HashMap<>();
map.put("name", "tiger");
map.put("age", "7");
map.put("birth", "20210309");
map.put("height", "120.1");
map.put("weight", "10.9");
User user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
// age=0
map.put("age", "7.1");
user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
// age=0
map.put("age", "a");
user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
map.remove("age");
// age=-1 初始值
user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
map.put("height", "a");
// height = 0.0
user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
map.put("birth", "2021 03 09");
// org.apache.commons.beanutils.ConversionException: Error converting 'String' to 'Date' using patterns 'yyyyMMdd, yyyy-MM-dd'
user = toBean(map,User.class);
System.out.println(JSON.toJSONString(user));
}
}
上一篇
下一篇
springboot禁用特定的自动配置类
go defer 延迟函数
java NIO http server
数据对象转换Object mapping
mysql时间函数
GO flag 命令行参数解析