Map类型做为一种常见的Java类型,经常在开发过程中使用,笔者最近遇到要将Map对象做为一种通用的参数变量,下传到多个业务类方法中,然后在各个业务类方法中将Map转换为指定类对象的情况。如何将Map转为各个不同的业务类对象,笔者通过com.alibaba.fastjson.JSON类来实现该转换。
例如需要将Map转为类ClearAcceptBatchOutDto对象。
1.实体类:ClearAcceptBatchOutDto
public class ClearAcceptBatchOutDto { /** * 产品编码 **/ private String productCode; /** * 支付类型和金额组(此处包含嵌套类PayTypeRequestDto) **/ private List<PayTypeRequestDto> payTypeGroup; /** * 手续费金额 **/ private Long poundageAmount; public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public List<PayTypeRequestDto> getPayTypeGroup() { return payTypeGroup; } public void setPayTypeGroup(List<PayTypeRequestDto> payTypeGroup) { this.payTypeGroup = payTypeGroup; } public Long getPoundageAmount() { return poundageAmount; } public void setPoundageAmount(Long poundageAmount) { this.poundageAmount = poundageAmount; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
2.实体类:PayTypeRequestDto
public class PayTypeRequestDto { /** * 支付方式 **/ private String payType; /** * 支付方式金额 **/ private Long amount; public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
3.将Map对象转换为对象ClearAcceptBatchOutDto:
public static void main(String[] args) { // 构造map对象(这里要确保key与对象中的属性变量名大小写一致) Map<String, Object> params = new HashMap<String, Object>(); params.put("productCode", "01010101"); params.put("poundageAmount", 222L); // 构造嵌套对象集合 List<Map<String, Object>> payTypeGroup = new ArrayList<Map<String, Object>>(); Map<String, Object> payTypeGroupMap = new HashMap<String, Object>(); payTypeGroupMap.put("payType", "01"); payTypeGroupMap.put("amount", 100L); payTypeGroup.add(payTypeGroupMap); Map<String, Object> payTypeGroupMap2 = new HashMap<String, Object>(); payTypeGroupMap2.put("payType", "02"); payTypeGroupMap2.put("amount", 101L); payTypeGroup.add(payTypeGroupMap2); params.put("payTypeGroup", payTypeGroup); // 将map转为ClearAcceptBatchOutDto对象 ClearAcceptBatchOutDto clearAcceptBatchOutDto = JSON.parseObject(JSON.toJSONString(params), ClearAcceptBatchOutDto.class); // 打印对象 System.out.println(params); System.out.println(clearAcceptBatchOutDto); }
以下控制台输出信息:
Map对象:
{poundageAmount=222, productCode=01010101, payTypeGroup=[{amount=100, payType=01}, {amount=101, payType=02}]}
ClearAcceptBatchOutDto对象:
com.suning.epp.css.clear.dto.ClearAcceptBatchOutDto@1c78c0b[productCode=01010101,payTypeGroup=[com.suning.epp.css.clear.dto.PayTypeRequestDto@843fce[payType=01,amount=100], com.suning.epp.css.clear.dto.PayTypeRequestDto@1dd3bcd[payType=02,amount=101]],poundageAmount=222]