Android JSONObject始终返回"null"; [英] Android JSONObject always returns "null"

查看:343
本文介绍了Android JSONObject始终返回"null";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Web服务器解析JSON.提取数据不是问题,但是当我尝试创建JSONObject时,它总是返回null.

I'm trying to parse JSON from my web server. Fetching data isn't the problem but when I try to create a JSONObject it always returns null.

我的JSON:

{"apikey":"c34750f19843vo45239o","error":false}

还有我的Java:

private class GetJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        JSONResult = null;
        HttpHandler sh = new HttpHandler();
        sh.HTTPMethod = DefaultMethod;

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(ApiUrl+tmpUrl);

        System.out.println("Response from "+ApiUrl+tmpUrl+": " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONResult = new JSONObject(jsonStr);

            } catch (final JSONException e) {
                System.out.println("Json parsing error: " + e.getMessage());
            }
        } else {
            System.out.println("Couldn't get json from server.");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        clearRequest();
    }

}

我尝试使用jsonStr.toString(),但结果相同.我也可以用Java记录我的JSON字符串,但无法解析.

I have tried with jsonStr.toString() but same result. I can also log my JSON string in Java but it isn't parsed.

这是它返回null的地方:

if(JSONResult != null && JSONResult.has("apikey")) {
    ApiKey = JSONResult.getString("apikey");
    System.out.println("Successfully got ApiKey: "+ApiKey);
}else{
    if(JSONResult == null){System.out.println("Is Null");}
}

对不起,我的英语不好.希望你能理解:)

Sorry for my bad English. Hope you understand :)

推荐答案

仅凭猜测,因为您的代码显示不足.

Just guessing, since you did not show enough of your code.

您很有可能在收到结果之前先对其进行检查. AsyncTask与您的主线程异步运行,您必须等到它完成后才能使用结果.

Most likely you check the result before it has been received. The AsyncTask runs asynchronously to your main thread and you would have to wait until it is finished before you can use the result.

实际上,这就是为什么存在onPostExecute方法的原因.这是处理结果的正确位置.

In fact, that's the reason why there is an onPostExecute method. This is the correct place to process the result.

这篇关于Android JSONObject始终返回"null";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆