4

您好,当我尝试从我的 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");
4

2 回答 2

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();
}

}
于 2013-03-18T14:36:06.077 回答
0

正如 Logcat 的第一行所示:

03-18 14:06:23.178: I/JSON(6719): myObject_Object: {"Nederlands":[{"length7": [{"word":"android"},{"word":"camping"}, {"word":"koekjes"}]}]}

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

jsonArray = myObject.getJSONArray("荷兰");

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

于 2013-03-18T14:37:25.217 回答