本人用的是fastjson的json处理工具,今天出现了一个奇怪的事情,在用containsKey的时候,打印出来的json字符串,没有这个key值,但是为什么会进去呢?测试了很久,觉得很诡异,后来问了一个踩坑多年的老司机,才知道问题所在,在json进行tostring的时候,如果值是null的时候,打印的时候,不会打印出value为null的key。
如下测试代码,以及结果:
package com.lk.test; import com.alibaba.fastjson.JSONObject; public class FastjsonTest { public static void main(String[] args) { JSONObject orginl_obj = new JSONObject(); orginl_obj.put("one", 1); orginl_obj.put("two", 2); orginl_obj.put("three", 3); orginl_obj.put("four", 4); System.out.println("原始的json值:" + orginl_obj.toString()); orginl_obj.put("four", null); System.out.println("此时将值变为null:" + orginl_obj.toJSONString()); if (orginl_obj.containsKey("four")) { System.out.println("the key is exist,and value is :" + orginl_obj.get("four")); } } }
结果:
原始的json值:{"four":4,"one":1,"two":2,"three":3} 此时将值变为null:{"one":1,"two":2,"three":3} the key is exist,and value is :null如果还有哪些坑,欢迎留言,一起探讨。这里只做了fastjson的测试,其他的json是否会这样,大家可以自行测试。