首页 > 技术文章 > object转其他类型

ybniu 2020-12-31 17:13 原文

遇到obj对象需要转成其他类型的对象,其他类型后续再加
public class ObjectUtil {

public static Map<String, Object> beanToMap(Object bean) {
return beanToMap(bean, false);
}

public static <T> void copyProperties(T source, T target, boolean ignoreNullProperty) {
BeanWrapper bw = new BeanWrapperImpl(source);
BeanWrapper bwTarget = new BeanWrapperImpl(target);
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
List<PropertyDescriptor> pdsTarget = Arrays.asList(bwTarget.getPropertyDescriptors());
List<String> targetPropertiesList = pdsTarget.stream().map(PropertyDescriptor::getName).collect(Collectors.toList());
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if ("class".equals(name)) {
continue;
}
if (targetPropertiesList.contains(name)) {
Object value = bw.getPropertyValue(name);
if (ignoreNullProperty) {
if (value != null) {
bwTarget.setPropertyValue(name, value);
}
} else {
bwTarget.setPropertyValue(name, value);
}
}
}
}

public static Map<String, Object> beanToMap(Object bean, boolean ignoreNullProperty) {
if (bean == null) {
return Collections.emptyMap();
}
BeanWrapper bw = new BeanWrapperImpl(bean);
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
Map<String, Object> map = new HashMap<>(pds.length, 1);
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
if ("class".equals(name)) {
continue;
}
Object value = bw.getPropertyValue(name);
if (ignoreNullProperty) {
if (value != null) {
map.put(name, value);
}
} else {
map.put(name, value);
}
}
return map;
}

public static boolean isJsonObject(String content) {
if (StringUtils.isBlank(content)) {
return false;
}
try {
JSONObject.parseObject(content);
return true;
} catch (Exception e) {
return false;
}
}

public static boolean isJsonArray(String content) {
if (StringUtils.isBlank(content)) {
return false;
}
try {
JSONArray.parseArray(content);
return true;
} catch (Exception e) {
return false;
}
}
}

推荐阅读