JAVA中将对象转为Map类型

之前讲过将Map转为JAVA对象的文章,那么问题来了,如果要把JAVA对象转为Map,又该怎么操作呢?
这里亲测了2个方法可行,但目前这2个方法都是基于简单JAVA Bean的情况(即Bean中不能嵌套非基本类型的对象)。

1.通过Introspector来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
    }

 以下是测试过程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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}

 

posted on   阿泰555  阅读(12641)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示