JSONObject 和 JsonObject

總結,方便後續查閱

1、區別:

1、JSONObjectAndroid原生的json類,通過import org.json.JSONObject來導入。

2、JsonObject 需要引入如下庫文件,通過com.google.gson.JsonObject來導入。

implementation 'com.google.code.gson:gson:2.8.5'

2、使用

通常Gson配合javaBean一起使用,相互轉換非常方便,這個以後有時間再總結單獨Gson的一些使用,今天總結剛剛使用中遇到的問題。

開發的時候,有時候服務器端返回的結果亂七八糟,沒有辦法配合javaBean使用的時候,如下可能需要單獨提取字段 success 狀態來分別做處理,下面總結 JSONObjectJsonObject 分別查詢單個字段方法。

{"product_key":"xxxxxx","success":true,"product_secret":"xxxxxxxx"}
{"success":false,"message":"error_params"}   
  • JSONObject
try {
    boolean success = JSONObject.getBoolean("success");
    if (success){
        // do sth
    }else{
        String message = JSONObject.getString("message");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

JSONObject 獲取時,如果返回數據中沒有獲取字段數據,就會返回 JSONException 異常

  • JsonObject
boolean success = jsonObject.get("success").getAsBoolean();
if (success) {
    // do sth
} else {
    String message = jsonObject.get("message").getAsString();
}

如果返回數據沒有 success字段時,會報錯:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.gson.JsonElement.getAsBoolean()' on a null object reference
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章