记一次对象序列化不打印value值为null的属性问题
背景:
开发时遇到问题,看日志的入参的busiData中没有intRate这个属性,后面转成map时,有个判断
if(map.containsKey("intRate")){ BigDecimal amt = new BigDecimal(datas.get("intRate")); }
一直报空指针异常,很郁闷这个参数是怎么添加进去的,而且值是null
测试代码如下:
@Test public void test() { String json = "{\"busiData\":{\"intRate1\":null,\"intRate2\":\"\",\"overdueFlag\":\"N\",\"firstDue\":\"51.594\",\"loanPeriod\":\"12\"},\"loanAmt\":6000.00,\"loanDays\":30,\"productCode\":\"360JINXIAO\",\"refundMethod\":\"03\"}"; CouponExchangeInput couponExchangeInput = JSONObject.parseObject(json, CouponExchangeInput.class); System.out.println(couponExchangeInput); logger.info("couponExchangeInput:{}", couponExchangeInput);
System.out.println("---------"); Map<Object, Object> map = new HashMap<>(); map.put("intRate1",null); map.put("intRate2",""); map.put("intRate3","aaa"); System.out.println(map); logger.info("map:{}", map); }
结果:
{"busiData":{"overdueFlag":"N","firstDue":"51.594","loanPeriod":"12","intRate2":""},"loanAmt":6000.00,"loanDays":30,"productCode":"360JINXIAO","refundMethod":"03"} INFO [main] [TestCoupon:301] - couponExchangeInput:{"busiData":{"overdueFlag":"N","firstDue":"51.594","loanPeriod":"12","intRate2":""},"loanAmt":6000.00,"loanDays":30,"productCode":"360JINXIAO","refundMethod":"03"} --------- {intRate3=aaa, intRate1=null, intRate2=} INFO [main] [TestCoupon:308] - map:{intRate3=aaa, intRate1=null, intRate2=}
结论:
对象的属性值为null,那么日志中不会打印该属性;属性值为空字符串,日志中会打印该属性
map中,不论value值为null还是为空字符串,日志中都会打印所有的键值对;