1、通过com.fastxml.jackson的ObjectMapper对象进行转换
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.convertValue(Object fromValue, Class<T> toValueType);
2、将java对象转换为json,然后将json转换成java对象
InsurePersonInfoDto applicantInfo = insureRelevantPersonInfoDto.getApplicantInfo();
ThirdPartInsurePersonInfo thirdPartApplicantInfo = JSON.parseObject(JSON.toJSONString(applicantInfo), new TypeReference<ThirdPartInsurePersonInfo>() {});
3、将java对象转换为json,然后将json转换成java对象
private static final ObjectMapper MAPPER = new ObjectMapper();
String jsonStr = MAPPER.writeValueAsString(obj);
RabbitMQDataDto detail = MAPPER.readValue(jsonStr, RabbitMQDataDto.class);
4、使用BeanUtils.copyProperties()拷贝一个bean中的属性到另一个bean中
- BeanUtils没有自动转换功能,遇到参数名相同,类型不同的参数不会进行赋值
- BeanUtils对部分属性不支持null的情况,Ineger、Boolean、Long等不支持
public static void copyProperties(Object dest, Object orig) {
try {
BeanUtils.copyProperties(dest, orig);
} catch (BeansException e) {
e.printStackTrace();
}
}