之前讲过将Map转为JAVA对象的文章,那么问题来了,如果要把JAVA对象转为Map,又该怎么操作呢?
这里亲测了2个方法可行,但目前这2个方法都是基于简单JAVA Bean的情况(即Bean中不能嵌套非基本类型的对象)。
1.通过Introspector来实现
public static Map<String, Object> objectToMap1(Object obj) { if (obj == null) { return null; } Map<String, Object> map = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter != null ? getter.invoke(obj) : null; map.put(key, value); } } catch (Exception e) { e.printStackTrace(); } return map; }
2.通过com.alibaba.fastjson.JSON来实现
@SuppressWarnings("unchecked") public static Map<String, Object> objectToMap2(Object obj) { return JSON.parseObject(JSON.toJSONString(obj), Map.class); }
以下是测试过程:
public static void main(String[] args) { SingleWithdrawCallBackMessage message = new SingleWithdrawCallBackMessage(); message.setAcqSerialNo(2017080100000999L); message.setBankNo("111111111111112"); message.setErrorMessage(""); message.setFundPayNo("1111111111111112"); message.setOrderTime("2017-08-01 12:00:00"); message.setOutOrderNo("2017080100000001"); message.setPoundageAmount(0L); message.setStatus(SingleWithdrawStatus.SINGLE_WITHDRAW_SUCCESS.getCode()); message.setWithdrawAmount(500L); Map<String, Object> map = null; map = objectToMap1(message); System.out.println(map); Map<String, Object> map2 = objectToMap2(message); System.out.println(map2); }
输出结果:
{fundPayNo=1111111111111112, poundageAmount=0, orderTime=2017-08-01 12:00:00, bankNo=111111111111112, errorMessage=, acqSerialNo=2017080100000999, withdrawAmount=500, outOrderNo=2017080100000001, status=03}
{fundPayNo=1111111111111112, poundageAmount=0, orderTime=2017-08-01 12:00:00, bankNo=111111111111112, errorMessage=, acqSerialNo=2017080100000999, withdrawAmount=500, outOrderNo=2017080100000001, status=03}