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,若是不得已須要都使用,那麼使用時請注意,避免因習慣,引發錯誤。