在平时的工作中,有时需要将Object转换成Map。笔者这里总结了两种将Object转成Map的方式方法。
方式 一:Jackson
引入jackson-databind
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
示例代码:
// 交易日志
TransferLog transferLog = new TransferLog();
transferLog.setId("1");
transferLog.setTransferType(1);
transferLog.setTransferTime(new Date());
transferLog.setAmount(new BigDecimal("2310.00"));
// 将object转成map
Map<String, Object> map = new ObjectMapper().convertValue(transferLog, Map.class);
// 转出转换结果
System.out.println("## 转换结果 ##");
System.out.println(new Gson().toJson(map));
转出结果:
## 转换结果 ##
{"id":"1","amount":2310.00,"transferTime":1613616565389,"transferType":1}
方式二:Hutool
引入hutool:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
示例代码:
// 交易日志
TransferLog transferLog = new TransferLog();
transferLog.setId("1");
transferLog.setTransferType(1);
transferLog.setTransferTime(new Date());
transferLog.setAmount(new BigDecimal("2310.00"));
// 方式二:hutool
Map<String, Object> hutoolMap = BeanUtil.beanToMap(transferLog);
// 转出转换结果
System.out.println("## 转换结果 ##");
System.out.println(new Gson().toJson(hutoolMap));
转出结果:
## 转换结果 ##
{"id":"1","amount":2310.00,"transferTime":"Feb 18, 2021 2:01:01 PM","transferType":1}