底層ObjectMapper
第一種
Map<String,Object> result = (Map<Sring,Object>)JsonUtils.jsonToObj(JsonUtils.objToJson(cafsOverdueCreaedTto,Map.class));
第二種:
org.apache.commons.beanUtils包下面的:就是後面的給前面數據即B賦值給A;
BeanUtils.copyProperties(A,B)
org.springframework.beans.BeanUtils這個包下面的就是A賦值給B,並且可以指定忽略的哪些屬性不賦值。
BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)
對source中null值會覆蓋掉traget中的該字段的值,解決方法就是擴展方法
public static String[] getNoValuePropertyNames (Object source) {
Assert.notNull(source, "傳遞的參數對象不能爲空");
final BeanWrapper beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
Set<String> noValuePropertySet = new HashSet<>();
Arrays.stream(pds).forEach(pd -> {
Object propertyValue = beanWrapper.getPropertyValue(pd.getName());
if (CommonUtils.isNull(propertyValue)) {
noValuePropertySet.add(pd.getName());
} else {
if (Iterable.class.isAssignableFrom(propertyValue.getClass())) {
Iterable iterable = (Iterable) propertyValue;
Iterator iterator = iterable.iterator();
if (!iterator.hasNext()) noValuePropertySet.add(pd.getName());
}
if (Map.class.isAssignableFrom(propertyValue.getClass())) {
Map map = (Map) propertyValue;
if (map.isEmpty()) noValuePropertySet.add(pd.getName());
}
}
});
String[] result = new String[noValuePropertySet.size()];
return noValuePropertySet.toArray(result);
}
或者用
hutool開源庫爲我們提供了更爲強大的Bean工具-BeanUtil,
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.14</version>
</dependency>
BeanUtil.copyProperties(oldDetail.get(),userDetail,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
核心代碼是CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)
詳情可以參考官方文檔 http://hutool.mydoc.io/#text_319433 。
第三種:org.dozer.Mapper 所有屬性包括id都會複製
Mapper mapper = new DozerBeanMapper();
mapper.map(cafsEnterpriseBase,CafsEnterpriseBaseHi.class);
JsonArray
JsonObject
*******************
[java] view plain copy print? BeanUtils.copyProperties("要轉換的類", "轉換後的類"); [java] view plain copy print? PropertyUtils.copyProperties("要轉換的類", "轉換後的類");