org json 和 fast json 掺杂使用引起的错误
1. 取值的不同
当所取得key不存在时:
org json 会抛异常
fast json 会返回null
示例:
com.alibaba.fastjson.JSONObject fastJson = new com.alibaba.fastjson.JSONObject();
String name = fastJson.getString("name");
// fastJson 正常输出 name:null
System.out.println("name:" + name);
org.json.JSONObject orgJson = new org.json.JSONObject();
//抛出异常:org.json.JSONException: JSONObject["name"] not found.
name = orgJson.getString("name");
System.out.println("name:" + name);
2. fast json 中 put org json
该操作异常,会放入空json
示例:
org.json.JSONObject orgJsonAddress = new org.json.JSONObject();
orgJsonAddress.put("country", "China");
orgJsonAddress.put("province", "Henan");
orgJsonAddress.put("city", "Zhengzhou");
com.alibaba.fastjson.JSONObject fastJson = new com.alibaba.fastjson.JSONObject();
fastJson.put("name", "Qingjiang Li");
fastJson.put("sex", 1);
fastJson.put("address", orgJsonAddress);
System.out.println(fastJson.toJSONString());
异常输出:
{
"address": {},
"sex": 1,
"name": "Qingjiang Li"
}
3. org json 中 put fast json
该操作正常
示例:
com.alibaba.fastjson.JSONObject fastJsonAddress = new com.alibaba.fastjson.JSONObject();
fastJsonAddress.put("country", "China");
fastJsonAddress.put("province", "Henan");
fastJsonAddress.put("city", "Zhengzhou");
org.json.JSONObject orgJson = new org.json.JSONObject();
orgJson.put("name", "Qingjiang Li");
orgJson.put("sex", 1);
orgJson.put("address", fastJsonAddress);
System.out.println(orgJson.toString());
输出正常:
{
"address": {
"country": "China",
"province": "Henan",
"city": "Zhengzhou"
},
"sex": 1,
"name": "Qingjiang Li"
}
结论:
在项目中,尽可能使用同一个种 JSON,如果不得已需要都使用,那么使用时请注意,避免因习惯,引起错误。