尝试从json字符串中获取json数组或json对象时的nullpointerexception

时间:2013-03-18 14:30:14

标签: android json

你好,当我尝试从我的jsonString获取一个对象时,我继续得到NPE。我尝试了很多东西甚至改变了我的json一次,但它只是没有用。 HTTPResponse工作正常,当我记录“myObject”时,它给出了正确的对象。但是当我试图让对象进入它时,它给了我一个NPE。我测试了json,它是有效的。我也尝试检索一个数组而不是一个对象,但它也提供了一个NPE。有人能告诉我如何解决这个问题。

我做了一个简单的jsontester活动来测试我的json:

public class JSONTester extends Activity {

private DefaultHttpClient createHttpClient() {
    HttpParams my_httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);
    DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);
    return httpclient;
}

MikeyJSON mJSON;

Button mBtnGo;
TextView mTxt1;
TextView mTxt2;
TextView mTxt3;
TextView mTxt4;
ProgressDialog mProgressDialog;
private String lang;        
private int length;     // 0 - 6 (length 7 to length 12)
private int wordPos;        // 0 - array length

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jsontester);

    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mTxt1 = (TextView) findViewById(R.id.txt1);
    mBtnGo = (Button) findViewById(R.id.btnGo);

}

public boolean isNumeric(String str) {

    for(int i=0;i<str.length();i++) {

        if(Character.isDigit(str.charAt(i))) {
            return true;
        }
    }
    return false;
}

public void testJSON(View view) {
    if(view==mBtnGo) {

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("loading");
        mProgressDialog.show();
        new DownloadNewWords().execute();
    }

}
private class DownloadNewWords extends AsyncTask<Void, Void, Void> {

    int mStatusCode = 0;
    String mResultString;
    Exception mConnectionException;

    @Override
    protected Void doInBackground(Void... args) {

            String fetchUrl = "http://www.mikeywebs.nl/json/jsonexample.html";
            DefaultHttpClient httpclient = createHttpClient();
        HttpGet httpget = new HttpGet(fetchUrl);

        try {
            HttpResponse response = httpclient.execute(httpget);
            StatusLine statusLine = response.getStatusLine();
            mStatusCode  = statusLine.getStatusCode();
                if (mStatusCode == 200){
                mResultString = EntityUtils.toString(response.getEntity());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            mConnectionException = e;
        } catch (IOException e) {
            e.printStackTrace();
            mConnectionException = e;
        }
        return null;            
    }

        @Override
    protected void onPostExecute(Void arg) {
        mProgressDialog.dismiss();
        if (mStatusCode  == 200){
            mJSON = new MikeyJSON(mResultString);   
            lang = "English";   //Integer.parseInt(langu);
            length = 7;  //Integer.parseInt(wordl);
            wordPos = 0;
            String getWord = mJSON.getResult(lang, length, wordPos);
            mTxt4.setText(getWord);

        }
        else {
            Toast.makeText(JSONTester.this, "Gegevens konden niet worden opgehaald. Controleer uw internetverbinding en probeer het opnieuw (" +mConnectionException.toString() + ")" , Toast.LENGTH_LONG).show();
            mJSON = null;
        }
    }
}

}

我使用的jsonclass是:

public class MikeyJSON {

private JSONObject myObject;
private JSONArray jsonArray;

int i;


public MikeyJSON(String jsonString) {
    Log.i("JSON", "jsonString: " + jsonString);
    try {
        JSONObject myObject = new JSONObject(jsonString);
        Log.i("JSON", "myObject_Object: " + myObject.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public String getResult(String lang, int length, int wordPos) {
    String word = "0";  
    //0 is Nederlands 1 is English
    int la = 0;
    if(lang.equals("English")) { 
        la = 1;
    }
    //make String length
    String le = "length" + Integer.toString(length);
    Log.i("PARSE", "get_length: " + le);

    //the json
    try {
        jsonArray = myObject.getJSONArray("galgjejson");
        Log.i("JSON", "jsonArray: " + jsonArray.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return word;        
}
}

这是json:

{ "galgjejson" : [
                { "Nederlands" :  [
                                        { "length7" : [ 
                                                            { "word" : "android" }, 
                                                            { "word" : "camping" },
                                                            { "word" : "koekjes" }
                                                        ]
                                        }
                                ]   
                },
                { "English" : [
                                        { "length7" : [ 
                                                            { "word" : "android" }, 
                                                            { "word" : "camping" },
                                                            { "word" : "koekjes" }
                                                        ]
                                        }
                                ]
                }               
            ]                                               
}

这是日志:

03-18 14:06:23.178: I/JSON(6719): myObject_Object: {"Nederlands":[{"length7":
[{"word":"android"},{"word":"camping"},{"word":"koekjes"}]}]}
03-18 14:06:23.178: I/PARSE(6719): get_length: length7
03-18 14:06:23.178: D/AndroidRuntime(6719): Shutting down VM
03-18 14:06:23.178: W/dalvikvm(6719): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
03-18 14:06:23.207: E/AndroidRuntime(6719): FATAL EXCEPTION: main
03-18 14:06:23.207: E/AndroidRuntime(6719): java.lang.NullPointerException
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.MikeyJSON.<init>(MikeyJSON.java:38)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:128)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:1)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask.finish(AsyncTask.java:631)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.os.Looper.loop(Looper.java:137)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at android.app.ActivityThread.main(ActivityThread.java:4745)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at java.lang.reflect.Method.invoke(Method.java:511)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-18 14:06:23.207: E/AndroidRuntime(6719):     at dalvik.system.NativeStart.main(Native Method)

哦,第38行是:

jsonArray = myObject.getJSONArray("galgjejson");

2 个答案:

答案 0 :(得分:1)

myObject很可能是null,因为你在课堂上拥有它,然后私密地在mikeyJSON中。你应该尝试:

private JSONObject myObject;
private JSONArray jsonArray;

int i;


public MikeyJSON(String jsonString) {
Log.i("JSON", "jsonString: " + jsonString);
try {
    myObject = new JSONObject(jsonString);
    Log.i("JSON", "myObject_Object: " + myObject.toString());
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}

看看那个JSON我很确定你可以使用构造函数中的字符串而不是JSONObject来创建JSONArray。

编辑的例子。

private JSONArray jsonArray;

int i;

public MikeyJSON(String jsonString) {
try {
    jsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}

答案 1 :(得分:0)

由于Logcat的第一行显示:

  

03-18 14:06:23.178:I / JSON(6719):myObject_Object:{“Nederlands”:[{“length7”:   [{ “词”: “机器人”},{ “字”: “野营”},{ “字”: “koekjes”}]}]}

此时,您已将JSONArray标记为“galgjejson”,因此您需要将第38行更改为:

  

jsonArray = myObject.getJSONArray(“Nederlands”);

这将为您提供下一个JSONArray进行处理