When JSONObject of value = null, key actually disappear?

We are using every day JSON, JSON but some of the pit you know it?

such as,

JSON when the value is null, key directly gone?

When the value to type Date, JSON.toJSONString print out is the time stamp, it is taken out of Date? Wait.

Ado, directly on the code

	public static void main(String[] args) {
		demoJSON();
		// demoMap();
	}

	/**
	 *  JSON单元测试接口
	 */
	public static void demoJSON() {
		JSONObject json = new JSONObject();
		json.put("date",new Date());
		json.put("demo","");
		json.put("key",null);
		System.out.println("json.toString:" + json.toJSONString());
		String keyDate = json.get("date") + ""; 
		String demo1 = json.get("demo") + "";
		String key1 = json.get("key") + "";  //这里转成了String
		String key2 = json.getString("key");

		String key1str = key1.toString();  //未报错
		// String key2str = key2.toString(); //报错:java.lang.NullPointerException
		System.out.println("json -- keyDate:" + keyDate);
		System.out.println("json -- key1:" + key1);
		System.out.println("json -- key2:" + key2);
		System.out.println("json -- key1str:" + key1str);
        // System.out.println("json -- key1str:" + key1str);
		System.out.println("");

	}
//打印出来的
json.toString:{"date":1573971907724,"demo":""}
json -- keyDate:Sun Nov 17 14:25:07 CST 2019
json -- key1:null
json -- key2:null
json -- key1str:null

visible,

1.JSONObject value of the data stored in date format, the time stamp is displayed as the toJSONString;

2. If the value is null, key will be directly canceled, get to the null value;

 

Therefore, we in the development process, the assignment to JSONObject, we must first determine whether the value is null, the timely processing.

 

Breakpoint look:

Published 52 original articles · won praise 122 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_39390545/article/details/103108427