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("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,如果不得已需要都使用,那麼使用時請注意,避免因習慣,引起錯誤。
###
以上是org json 和 fast json使用時所出現的問題及解決辦法的詳細內容。更多資訊請關注PHP中文網其他相關文章!