1. 程式人生 > 實用技巧 >object轉其他型別

object轉其他型別

遇到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;
}
}
}