如何检查json是否在android中有此对象

时间:2013-10-06 13:06:17

标签: android json object

我使用asynctask从远程url获取json数据,但有时这个url会在json数据中返回错误,如下所示:

{
   "error": {
      "message": "(#803) Some of the aliases you requested do not exist: RNN.NES",
      "type": "OAuthException",
      "code": 803
   }
}

在doInBackground中,我检查json是否有错误..

if(true){取消asynctask并使用消息显示toast

cancel(true)

但是当我尝试输入包含错误对象的无效网址时,它看不到条件并强制停止应用

这是我的代码:

@Override
        protected Void doInBackground(String... params) {
            db.open();
            try {
                // Creating JSON Parser instance
                JSONParser jParser = new JSONParser();

                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(params[0]);
                // addPageData(params[0]);

                if (json.has("error") == true) {
                    Log.e("error", "true");
                    toastMsg = "This username is invalid";
                    cancel(true);
                } else {

                    name = json.getString("name");
                    Log.e("error", name);
//                  category = json.getString("category");
                    fid = json.getString("id");
                    if (db.checkPage(fid)) {
                        toastMsg = "This page is already added";
                        cancel(true);
                    }

                    String picture = json.getJSONObject("picture").getJSONObject("data").getString("url");
                    picName = downloadImage(picture, fid);
                }

                db.closeDatabase();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
       @Override
    protected void onCancelled() {
        mProgressDialog.dismiss();
        Toast.makeText(context, toastMsg, Toast.LENGTH_LONG).show();
    }

jsonParser.java

package com.engahmedphp.facebookcollector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // ==============================================================================
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        // try {
        // defaultHttpClient
        // DefaultHttpClient httpClient = new DefaultHttpClient();
        // // HttpFeed httpFeed = new HttpFeed(url);
        //
        // HttpGet httpGet = new HttpGet(url);
        //
        // HttpResponse httpResponse = httpClient.execute(httpGet);
        // HttpEntity httpEntity = httpResponse.getEntity();
        // is = httpEntity.getContent();

        try {
            URL newURL = new URL(url);

            HttpURLConnection con = (HttpURLConnection) newURL.openConnection();
            is = con.getInputStream();

        } catch (MalformedURLException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // DefaultHttpClient httpClient = new DefaultHttpClient();
        // // HttpFeed httpFeed = new HttpFeed(url);
        //
        // HttpGet httpGet = new HttpGet(url);
        // HttpResponse httpResponse = null;
        // try {
        // httpResponse = httpClient.execute(httpGet);
        //
        // } catch (UnsupportedEncodingException e) {
        // e.printStackTrace();
        // } catch (ClientProtocolException e) {
        // e.printStackTrace();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }

        try {
            // HttpEntity httpEntity = httpResponse.getEntity();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();

            // System.out.println(json);
            // System.out.println(httpEntity);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

它认为它不包含错误对象然后他移动到else子句并强制关闭

这是我的logcat ..我认为它包含一些可能对您有用的信息

10-06 15:04:45.539: E/JSON Parser(7183): Error parsing data org.json.JSONException: End of input at character 0 of 
10-06 15:04:45.539: W/System.err(7183): org.json.JSONException: No value for name
10-06 15:04:45.539: W/System.err(7183):     at org.json.JSONObject.get(JSONObject.java:354)
10-06 15:04:45.539: W/System.err(7183):     at org.json.JSONObject.getString(JSONObject.java:510)
10-06 15:04:45.539: W/System.err(7183):     at com.engahmedphp.facebookcollector.General$MyAsyncTask.doInBackground(General.java:148)
10-06 15:04:45.539: W/System.err(7183):     at com.engahmedphp.facebookcollector.General$MyAsyncTask.doInBackground(General.java:1)
10-06 15:04:45.539: W/System.err(7183):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-06 15:04:45.539: W/System.err(7183):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-06 15:04:45.539: W/System.err(7183):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-06 15:04:45.539: W/System.err(7183):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
10-06 15:04:45.539: W/System.err(7183):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
10-06 15:04:45.539: W/System.err(7183):     at java.lang.Thread.run(Thread.java:1096)
10-06 15:04:45.589: W/dalvikvm(7183): threadid=1: thread exiting with uncaught exception (group=0x400207d8)
10-06 15:04:45.679: E/AndroidRuntime(7183): FATAL EXCEPTION: main
10-06 15:04:45.679: E/AndroidRuntime(7183): java.lang.IllegalArgumentException: the bind value at index 1 is null
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:234)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteQuery.bindString(SQLiteQuery.java:182)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:48)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1454)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1338)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1293)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1373)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.engahmedphp.facebookcollector.DAOPages.getPageData(DAOPages.java:183)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.engahmedphp.facebookcollector.General.getPagePrefs(General.java:180)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.engahmedphp.facebookcollector.General.insertPageAndSetAlarmAndPrefs(General.java:207)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.engahmedphp.facebookcollector.General$MyAsyncTask.onPostExecute(General.java:113)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.engahmedphp.facebookcollector.General$MyAsyncTask.onPostExecute(General.java:1)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.os.AsyncTask.finish(AsyncTask.java:417)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.os.Looper.loop(Looper.java:123)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at android.app.ActivityThread.main(ActivityThread.java:4633)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at java.lang.reflect.Method.invokeNative(Native Method)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at java.lang.reflect.Method.invoke(Method.java:521)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-06 15:04:45.679: E/AndroidRuntime(7183):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

您的问题出现在您的JSON解析器中:

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

你以某种方式将一个完全空的字符串传递给对象json,因此它会抛出一个JSONException。

由于您正在为jObj使用静态成员,并且上面的catch块未将其设置为null以指示存在错误,因此您将从JSONParser的任何实例返回此方法的最后一个有效jObj,因此json.has("error")可能会返回false。

我看不出有任何理由将jObj存储为静态成员,因此我只想将其更改为在上面引用的代码之前声明的局部变量。然后在我上面引用的catch块中,在记录错误后返回null。在doInBackground方法中,您可以将if语句更改为:

if (json==null){
    //Log whatever kind of error could cause this, toast user, and cancel(true).
} else if (json.has("error")) {
    ...