zoukankan      html  css  js  c++  java
  • json的containsKey的判断,明明没有这个key,为什么判断显示有?

        本人用的是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是否会这样,大家可以自行测试。
  • 相关阅读:
    如何使用angularjs实现文本框设置值
    如何使用angularjs实现文本框获取焦点
    electron的安装
    linux中升级jdk的方法
    linux中添加开机自启服务的方法
    liunx系统安装tomcat的方法
    liunx系统安装jdk的方法
    常用linux命令
    ResourceBundle的使用
    查看Linux系统版本的命令
  • 原文地址:https://www.cnblogs.com/timeout/p/10145640.html
Copyright © 2011-2022 走看看