JSONObject处理字符串null的坑

在java处理JSON数据时,出现value为"null"的不能正常打印。
在打印出value为“null”时,直接输出null,而不是null字符串。
例子:

import net.sf.json.JSONObject;
public class Test{
	public static void main(String[] args) throws Exception{
		JSONObject backJsonObject = new JSONObject();
		backJsonObject.put("111", "null");
		backJsonObject.put("222", null);
		backJsonObject.put("333", "11");
		String backString = backJsonObject.toString();
		System.out.println(backString);
	}
	
}
输出结果:
{"111":null,"333":"11"}
value为null的不能输出,value为"null"的输出为null,其他的正常输出。


想要把"null"的正常输出,则需要特殊处理下,

import net.sf.json.JSONObject;
public class Test{
	public static void main(String[] args) throws Exception{
		JSONObject backJsonObject = new JSONObject();
		backJsonObject.put("111", "null");
		backJsonObject.put("222", null);
		backJsonObject.put("333", "11");
		String backString = backJsonObject.toString();
		String ans = backString.replaceAll(":null,", ":\"null\",");
		System.out.println(ans);
	}
	
}
输出:
{"111":"null","333":"11"}







你可能感兴趣的:(JSONObject处理字符串null的坑)