简体   繁体   English

仅对某些GSON方法调用返回JsonObject Null

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

EDITED MY QUESTION: 编辑我的问题:

I've been working on my first ever programming and Android project. 我一直在从事我的第一个编程和Android项目。

In the following code I receive a: 在以下代码中,我收到:

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

for trying to call a method on my result JSONOBJECT which was retrieved using a networking library: https://github.com/koush/ion and is being parsed using google GSON library. 尝试在我的结果 JSONOBJECT上调用方法,该方法是使用网络库检索的: https : //github.com/koush/ion ,正在使用Google GSON库进行解析。

A toast string message and a log.v reveals that the JSON object is being successfully passed with all the necessary elements included.(Or maybe not passed completely? The Log.v cuts off after some point.) 吐司字符串消息和log.v表明JSON对象已被成功传递并包含所有必需的元素。(或者可能未完全传递?Log.v会在某个时间点后切断。)

My confusion lies in the ability to call the toString() GSON method on result which leads to a successful toast message, while attempting to call any other GSON method like result.get(images_count).toString leads to my error. 我的困惑在于对结果调用toString()GSON方法的能力,这会导致成功的Toast消息,而尝试调用任何其他GSON方法(如result.get(images_count).toString)则会导致我的错误。 I tried to use if(result.isJsonNull()) before executing my code to make sure that result was not null, but even if result.isJsonNull() returns false my method calls returns the error. 我尝试在执行代码之前使用if(result.isJsonNull())以确保结果不为空,但是即使result.isJsonNull()返回false,我的方法调用也会返回错误。

My 2 Part Question 我的第二部分问题

What is causing my returned JsonObject result to successfully execute some GSON library methods sucessfully(like toString()), while returning a NullPointer Exception for others as when I atttempt to reach a json element member through .get(string member)? 是什么导致我返回的JsonObject 结果成功地成功执行了某些GSON库方法(如toString()),而当我尝试通过.get(string member)到达json元素成员时却为其他人返回了NullPointer Exception?

In the future, how could I place/recognize checkpoints where an object might return a NullPointerException? 将来,我如何放置/识别对象可能返回NullPointerException的检查点? So far I only use Logging or Toasts to display current object/variable values. 到目前为止,我仅使用Logging或Toasts来显示当前的对象/变量值。 THANKS ANSWERED BY BRONX. 谢谢布朗克斯。 I have to use breakpoints. 我必须使用断点。

Code that results in the NullPointer Exception: (I have replaced my CLient-ID with xxxxxxx in order to keep it a secret from the internet). 导致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();

                     }
                    }
                });
    }

Here is the LogCat which includes the successfully retrieved JSON Object(We can see the JSON Object in the Log.) The Json object DOES contain the element images_count. 这是LogCat,其中包含成功检索到的JSON对象(我们可以在日志中看到JSON对象。)Json对象确实包含元素images_count。 LogCat: 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

Ok looking at the logCat it seems that the entire JSon Object is not being printed out. 好了,看看logCat似乎没有打印出整个JSon对象。 Is this a limitation of what Log.v can print? 这是Log.v可以打印的内容的限制吗? Or am I getting a Null object reference because the network call isn't returning a fully complete object? 还是因为网络调用未返回完全完整的对象,我是否获得了Null对象引用?

An example of what a Json object retreived from Imgur's Api looks like: https://api.imgur.com/models/album 从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
}

if you can post an example of the json response we can help you better. 如果您可以发布json响应的示例,我们可以为您提供更好的帮助。 However from what i can see the JsonElement "images_count" doesn't exists, and so you get the NullPointerException. 但是,从我可以看到的JsonElement“ images_count”不存在,所以您得到NullPointerException。

From what i can see, if i try that calls from the browser i get this json response: 从我所看到的,如果我尝试从浏览器调用,我会收到以下json响应:

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

It is possibile that you don't add some query parameter request from the WebService. 您可以不从WebService添加一些查询参数请求。

PS: To display current object/variable values you need to use breakpoints and run your application in debug mode PS:要显示当前对象/变量值,您需要使用断点并在调试模式下运行应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM