当value为null时
@Test
public void testFastJsonAndJackson() throws Exception {
HashMap<String, Student> map = new HashMap<>();
map.put("aa", new Student("01", "张三"));
map.put("bb", new Student("02", "李四"));
map.put("cc",null);
map.put("dd",new Student());
// map.put(null, new Student("03", "王五"));
map.forEach((k, v) -> System.out.println(k + ":" + v));
System.out.println("================================");
System.out.println("map: " + map);
System.out.println("================================");
//fastJson
String s = JSON.toJSONString(map);
System.out.println("用fastJson转json字符串: " + s);
String s1 = JSONObject.toJSONString(map);
System.out.println("用fastJson转json字符串: " + s1);
System.out.println("================================");
//jackson
ObjectMapper objectMapper = new ObjectMapper();
String s2 = objectMapper.writeValueAsString(map);
System.out.println("用jackson转json字符串: " + s2);
}
运行结果1
当key为null时
@Test
public void testFastJsonAndJackson() throws Exception {
HashMap<String, Student> map = new HashMap<>();
map.put("aa", new Student("01", "张三"));
map.put("bb", new Student("02", "李四"));
map.put("cc",null);
map.put("dd",new Student());
map.put(null, new Student("03", "王五"));
map.forEach((k, v) -> System.out.println(k + ":" + v));
System.out.println("================================");
System.out.println("map: " + map);
System.out.println("================================");
//fastJson
String s = JSON.toJSONString(map);
System.out.println("用fastJson转json字符串: " + s);
String s1 = JSONObject.toJSONString(map);
System.out.println("用fastJson转json字符串: " + s1);
System.out.println("================================");
//jackson
ObjectMapper objectMapper = new ObjectMapper();
String s2 = objectMapper.writeValueAsString(map);
System.out.println("用jackson转json字符串: " + s2);
运行结果2
总结
- fastjson会转化key为null时情况,但是会过滤掉value为null的键值对;
- jackson会转化value为null的情况,但是key为null时会报错;
结论
在fastjson或jackson时,map中一定要避免null值,可以给一个空的类型,字符串/对象/数组/list之类的.