簡體   English   中英

僅對某些GSON方法調用返回JsonObject Null

[英]Returned JsonObject Null for only some GSON method calls

編輯我的問題:

我一直在從事我的第一個編程和Android項目。

在以下代碼中,我收到:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.gson.JsonElement.toString()' on a null object reference

嘗試在我的結果 JSONOBJECT上調用方法,該方法是使用網絡庫檢索的: https : //github.com/koush/ion ,正在使用Google GSON庫進行解析。

吐司字符串消息和log.v表明JSON對象已被成功傳遞並包含所有必需的元素。(或者可能未完全傳遞?Log.v會在某個時間點后切斷。)

我的困惑在於對結果調用toString()GSON方法的能力,這會導致成功的Toast消息,而嘗試調用任何其他GSON方法(如result.get(images_count).toString)則會導致我的錯誤。 我嘗試在執行代碼之前使用if(result.isJsonNull())以確保結果不為空,但是即使result.isJsonNull()返回false,我的方法調用也會返回錯誤。

我的第二部分問題

是什么導致我返回的JsonObject 結果成功地成功執行了某些GSON庫方法(如toString()),而當我嘗試通過.get(string member)到達json元素成員時卻為其他人返回了NullPointer Exception?

將來,我如何放置/識別對象可能返回NullPointerException的檢查點? 到目前為止,我僅使用Logging或Toasts來顯示當前的對象/變量值。 謝謝布朗克斯。 我必須使用斷點。

導致NullPointer異常的代碼:(為了防止來自互聯網的秘密,我已將我的CLient-ID替換為xxxxxxx)。

 Future<JsonObject> loading;

    private void load() {
        // don't attempt to load more if a load is already in progress
        if (loading != null && !loading.isDone() && !loading.isCancelled())
            return;

        // load the tweets from album : gQxwy https://api.imgur.com/3/album/{id}
        //https://api.imgur.com/3/album/{id}/images
        String url = "https://api.imgur.com/3/album/gQxwy.json";

        // This request loads a URL as JsonObject and invokes
        // a callback on completion.
        loading = Ion.with(this)
                .load(url)
                .setHeader("Authorization", "Client-ID " + "xxxxxxxxxxxxxxx")
                .setLogging("ION_VERBOSE_LOGGING", Log.VERBOSE)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {


                        // this is called back onto the ui thread, no Activity.runOnUiThread or Handler.post necessary.
                        if (e != null) {
                            Toast.makeText(Imgur.this, "Error loading tweets", Toast.LENGTH_LONG).show();
                            return;
                        }

                        //Here i test if the object is Null.It goes directly to excute else, showing that the object is not Null.
                          if(result.isJsonNull()){
                              Toast.makeText(Imgur.this, result.toString(), Toast.LENGTH_LONG).show();
                          }else {

                              Log.v("JSONOBJECT_STRING", result.toString());

                              Toast.makeText(Imgur.this, result.get("images_count").toString(), Toast.LENGTH_LONG).show();

                     }
                    }
                });
    }

這是LogCat,其中包含成功檢索到的JSON對象(我們可以在日志中看到JSON對象。)Json對象確實包含元素images_count。 logcat的:

03-21 21:24:26.395    8035-8061/? D/ION_VERBOSE_LOGGING﹕ (353 ms) https://api.imgur.com/3/album/gQxwy.json: Connection successful
03-21 21:24:26.405    8035-8061/? D/ION_VERBOSE_LOGGING﹕ (363 ms) https://api.imgur.com/3/album/gQxwy.json: Recycling keep-alive socket
03-21 21:24:26.407    8035-8035/? V/JSONOBJECT_STRING﹕ {"data":{"id":"gQxwy","title":"playlist","description":null,"datetime":1425872636,"cover":"c7iJOmN","cover_width":160,"cover_height":120,"account_url":"JohnnyJem","account_id":18800283,"privacy":"public","layout":"blog","views":574,"link":"http://imgur.com/a/gQxwy","favorite":false,"nsfw":null,"section":null,"images_count":10,"images":[{"id":"c7iJOmN","title":"Title","description":"Description","datetime":1425872636,"type":"image/gif","animated":true,"width":160,"height":120,"size":65008,"views":1175,"bandwidth":76384400,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/c7iJOmN.gifv","webm":"http://i.imgur.com/c7iJOmN.webm","mp4":"http://i.imgur.com/c7iJOmN.mp4","link":"http://i.imgur.com/c7iJOmN.gif","looping":true},{"id":"SYRfZPy","title":"Title","description":"Description","datetime":1425872638,"type":"image/gif","animated":true,"width":160,"height":120,"size":139574,"views":1054,"bandwidth":147110996,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/SYRfZPy.gifv","webm":"http://i.imgur.com/SYRfZPy.webm","mp4":"http://i.imgur.com/SYRfZPy.mp4","link":"http://i.imgur.com/SYRfZPy.gif","looping":true},{"id":"1aD2tdR","title":"Title","description":"Description","datetime":1425872639,"type":"image/gif","animated":true,"width":160,"height":120,"size":117092,"views":882,"bandwidth":103275144,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/1aD2tdR.gifv","webm":"http://i.imgur.com/1aD2tdR.webm","mp4":"http://i.imgur.com/1aD2tdR.mp4","link":"http://i.imgur.com/1aD2tdR.gif","looping":true},{"id":"7UzUF79","title":"Title","description":"Description","datetime":1425872641,"type":"image/gif","animated":true,"width":160,"height":120,"size":146703,"views":785,"bandwidth":115161855,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/7UzUF79.gifv","webm":"http://i.imgur.com/7UzUF79.webm","mp4":"http://i.imgur.com/7UzUF79.mp4","link":"http://i.imgur.com/7UzUF79.gif","looping":true},{"id":"3PKeSiW","title":"Title","description":"Description","datetime":1425872642,"type":"image/gif","animated":true,"width":160,"height":120,"size":136914,"views":753,"bandwidth":103096242,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/3PKeSiW.gifv","webm":"http://i.imgur.com/3PKeSiW.webm","mp4":"http://i.imgur.com/3PKeSiW.mp4","link":"http://i.imgur.com/3PKeSiW.gif","looping":true},{"id":"o3UBVgR","title":"Title","description":"Description","datetime":1425872644,"type":"image/gif","animated":true,"width":160,"height":120,"size":129046,"views":483,"bandwidth":62329218,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/o3UBVgR.gifv","webm":"http://i.imgur.com/o3UBVgR.webm","mp4":"http://i.imgur.com/o3UBVgR.mp4","link":"http://i.imgur.com/o3UBVgR.gif","looping":true},{"id":"qraDqOQ","title":"Title","description":"Description","datetime":1425872645,"type":"image/gif","animated":true,"width":160,"height":120,"size":93116,"views":466,"bandwidth":43392056,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/qraDqOQ.gifv","webm":"http://i.imgur.com/qraDqOQ.webm","mp4":"http://i.imgur.com/qraDqOQ.mp4","link":"http://i.imgur.com/qraDqOQ.gif","looping":true},{"id":"K9PuB3S","title":"Title","description":"Description","datetime":1425872647,"type":"image/gif","animated":true,"width":160,"height":120,"size":84323,"views":481,"bandwidth":40559363,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"gifv":"http://i.imgur.com/K9PuB3S.gifv","webm":"http://i.imgur.com/K9PuB3S.webm","mp4":"http://i.imgur.com/K9PuB3S.mp4","link":"http://i.imgur.com/K9PuB3S.gif","looping":true},{"id":"p3whCAz","title":"Title","descriptio

03-21 21:24:26.408    8035-8035/? D/AndroidRuntime﹕ Shutting down VM
03-21 21:24:26.408    8035-8035/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.johnnymolina.nextphase, PID: 8035
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.gson.JsonElement.toString()' on a null object reference
            at com.johnnymolina.nextphase.activities.Imgur$2.onCompleted(Imgur.java:116)
            at com.johnnymolina.nextphase.activities.Imgur$2.onCompleted(Imgur.java:98)
            at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:107)
            at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:141)
            at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:128)
            at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:246)
            at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:57)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-21 21:24:26.411    6534-6864/? W/ActivityManager﹕ Force finishing activity com.johnnymolina.nextphase/.activities.Imgur
03-21 21:24:26.412    6534-6864/? W/ActivityManager﹕ Force finishing activity com.johnnymolina.nextphase/.activities.MainActivity

好了,看看logCat似乎沒有打印出整個JSon對象。 這是Log.v可以打印的內容的限制嗎? 還是因為網絡調用未返回完全完整的對象,我是否獲得了Null對象引用?

從Imgur的Api中檢索到的Json對象的示例如下所示: https : //api.imgur.com/models/album

{
    "data": {
        "id": "lDRB2",
        "title": "Imgur Office",
        "description": null,
        "datetime": 1357856292,
        "cover": "24nLu",
        "account_url": "Alan",
        "account_id": 4,
        "privacy": "public",
        "layout": "blog",
        "views": 13780,
        "link": "http://alanbox.imgur.com/a/lDRB2",
        "images_count": 11,
        "images": [
            {
                "id": "24nLu",
                "title": null,
                "description": null,
                "datetime": 1357856352,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 855658,
                "views": 135772,
                "bandwidth": 116174397976,
                "link": "http://i.imgur.com/24nLu.jpg"
            },
            {
                "id": "Ziz25",
                "title": null,
                "description": null,
                "datetime": 1357856394,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 919391,
                "views": 135493,
                "bandwidth": 124571044763,
                "link": "http://i.imgur.com/Ziz25.jpg"
            },
            {
                "id": "9tzW6",
                "title": null,
                "description": null,
                "datetime": 1357856385,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 655028,
                "views": 135063,
                "bandwidth": 88470046764,
                "link": "http://i.imgur.com/9tzW6.jpg"
            },
            {
                "id": "dFg5u",
                "title": null,
                "description": null,
                "datetime": 1357856378,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 812738,
                "views": 134704,
                "bandwidth": 109479059552,
                "link": "http://i.imgur.com/dFg5u.jpg"
            },
            {
                "id": "oknLx",
                "title": null,
                "description": null,
                "datetime": 1357856338,
                "type": "image/jpeg",
                "animated": false,
                "width": 1749,
                "height": 2332,
                "size": 717324,
                "views": 32938,
                "bandwidth": 23627217912,
                "link": "http://i.imgur.com/oknLx.jpg"
            },
            {
                "id": "OL6tC",
                "title": null,
                "description": null,
                "datetime": 1357856321,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 1443262,
                "views": 32346,
                "bandwidth": 46683752652,
                "link": "http://i.imgur.com/OL6tC.jpg"
            },
            {
                "id": "cJ9cm",
                "title": null,
                "description": null,
                "datetime": 1357856330,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 544702,
                "views": 31829,
                "bandwidth": 17337319958,
                "link": "http://i.imgur.com/cJ9cm.jpg"
            },
            {
                "id": "7BtPN",
                "title": null,
                "description": null,
                "datetime": 1357856369,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 844863,
                "views": 31257,
                "bandwidth": 26407882791,
                "link": "http://i.imgur.com/7BtPN.jpg"
            },
            {
                "id": "42ib8",
                "title": null,
                "description": null,
                "datetime": 1357856424,
                "type": "image/jpeg",
                "animated": false,
                "width": 2592,
                "height": 1944,
                "size": 905073,
                "views": 30945,
                "bandwidth": 28007483985,
                "link": "http://i.imgur.com/42ib8.jpg"
            },
            {
                "id": "BbwIx",
                "title": null,
                "description": null,
                "datetime": 1357856360,
                "type": "image/jpeg",
                "animated": false,
                "width": 1749,
                "height": 2332,
                "size": 662413,
                "views": 30107,
                "bandwidth": 19943268191,
                "link": "http://i.imgur.com/BbwIx.jpg"
            },
            {
                "id": "x7b91",
                "title": null,
                "description": null,
                "datetime": 1357856406,
                "type": "image/jpeg",
                "animated": false,
                "width": 1944,
                "height": 2592,
                "size": 618567,
                "views": 29259,
                "bandwidth": 18098651853,
                "link": "http://i.imgur.com/x7b91.jpg"
            }
        ]
    },
    "success": true,
    "status": 200
}

如果您可以發布json響應的示例,我們可以為您提供更好的幫助。 但是,從我可以看到的JsonElement“ images_count”不存在,所以您得到NullPointerException。

從我所看到的,如果我嘗試從瀏覽器調用,我會收到以下json響應:

{"data":{"error":"Authentication required","request":"\/3\/album\/gQxwy.json","method":"GET"},"success":false,"status":401}

您可以不從WebService添加一些查詢參數請求。

PS:要顯示當前對象/變量值,您需要使用斷點並在調試模式下運行應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM