SON数组或JSON对象时的NullPointerExcepti

SON数组或JSON对象时的NullPointerExcepti

本文介绍了试图从JSON字符串JSON数组或JSON对象时的NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我不断收到NPE当我尝试从我的jsonString获取的对象。我尝试了很多事情,甚至改变了我的JSON次coople但它只是不工作。该HTT presponse工作正常,当我登录myObject的它给合适的对象。但是,当我试图让对象是它给了我一个NPE。我测试的JSON,它是有效的。我也试过来检索,而不是数组的对象,但它也给出了一个NPE。谁能告诉我如何解决这个问题。

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

 公共类JSONTester延伸活动{私人DefaultHttpClient createHttpClient(){
    的HttpParams my_httpParams =新BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(my_httpParams,3000);
    SchemeRegistry注册表=新SchemeRegistry();
    registry.register(新计划(HTTP,PlainSocketFactory.getSocketFactory(),80));
    ThreadSafeClientConnManager multiThreadedConnectionManager =新ThreadSafeClientConnManager(my_httpParams,注册表);
    DefaultHttpClient的HttpClient =新DefaultHttpClient(multiThreadedConnectionManager,my_httpParams);
    返回HttpClient的;
}MikeyJSON mJSON;按钮mBtnGo;
TextView的mTxt1;
TextView的mTxt2;
TextView的mTxt3;
TextView的mTxt4;
ProgressDialog mProgressDialog;
私人字符串郎;
私人诠释长度; // 0 - 6(长7〜长12)
私人诠释wordPos; // 0 - 数组的长度@覆盖
保护无效的onCreate(捆绑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 =(按钮)findViewById(R.id.btnGo);}公共布尔ISNUMERIC(字符串str){    的for(int i = 0; I< str.length();我++){        如果(Character.isDigit(str.charAt(ⅰ))){
            返回true;
        }
    }
    返回false;
}公共无效testJSON(查看视图){
    如果(查看== mBtnGo){        mProgressDialog =新ProgressDialog(本);
        mProgressDialog.setMessage(装载);
        mProgressDialog.show();
        新DownloadNewWords()执行();
    }}
私有类DownloadNewWords扩展的AsyncTask<太虚,太虚,太虚> {    INT MSTATUS code = 0;
    串mResultString;
    异常mConnectionException;    @覆盖
    保护无效doInBackground(无效参数... args){            字符串fetchUrl =htt​​p://www.mikeywebs.nl/json/jsonexample.html;
            DefaultHttpClient的HttpClient = createHttpClient();
        HTTPGET HTTPGET =新HTTPGET(fetchUrl);        尝试{
            HTT presponse响应= httpclient.execute(HTTPGET);
            状态行状态行= response.getStatusLine();
            MSTATUS code = statusLine.getStatus code();
                如果(MSTATUS code == 200){
                mResultString = EntityUtils.toString(response.getEntity());
            }
        }赶上(ClientProtocolException E){
            e.printStackTrace();
            mConnectionException = E;
        }赶上(IOException异常五){
            e.printStackTrace();
            mConnectionException = E;
        }
        返回null;
    }        @覆盖
    保护无效onPostExecute(无效ARG){
        mProgressDialog.dismiss();
        如果(MSTATUS code == 200){
            mJSON =新MikeyJSON(mResultString);
            LANG =英语; //Integer.parseInt(langu);
            长度= 7; //Integer.parseInt(wordl);
            wordPos = 0;
            字符串屏幕取词= mJSON.getResult(郎,长,wordPos);
            mTxt4.setText(屏幕取词);        }
        其他{
            Toast.makeText(JSONTester.this,Gegevens konden Niet的沃登opgehaald Controleer UW internetverbinding连接probeer HET opnieuw(+ mConnectionException.toString()+),Toast.LENGTH_LONG).show();
            mJSON = NULL;
        }
    }
}}

和我用的是jsonclass:

 公共类MikeyJSON {私人的JSONObject myObject的;
私人JSONArray jsonArray;INT I;
公共MikeyJSON(字符串jsonString){
    Log.i(JSON,jsonString:+ jsonString);
    尝试{
        JSONObject的myObject的=新的JSONObject(jsonString);
        Log.i(JSON,myObject_Object:+ myObject.toString());
    }赶上(JSONException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }}公共字符串的getResult(字符串郎,诠释长度,诠释wordPos){
    串字=0;
    // 0荷兰1是英语
    INT LA = 0;
    如果(lang.equals(英语)){
        LA = 1;
    }
    //使字符串长度
    串乐=长度+ Integer.toString(长);
    Log.i(PARSE,get_length:+了);    //将JSON
    尝试{
        jsonArray = myObject.getJSONArray(galgjejson);
        Log.i(JSON,jsonArray:+ jsonArray.toString());
    }赶上(JSONException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }    返回字;
}
}

下面是JSON:

  {galgjejson:[
                {荷兰:[
                                        {length7:[
                                                            {词:机器人},
                                                            {词:露营},
                                                            {词:koekjes}
                                                        ]
                                        }
                                ]
                },
                { 英语 : [
                                        {length7:[
                                                            {词:机器人},
                                                            {词:露营},
                                                            {词:koekjes}
                                                        ]
                                        }
                                ]
                }
            ]
}

和这里是日志:

  03-18 14:06:23.178:I / JSON(6719):myObject_Object:{荷兰:[{length7:
[{词:机器人},{字:露营},{字:koekjes}]}]}
03-18 14:06:23.178:I / PARSE(6719):get_length:length7
03-18 14:06:23.178:D / AndroidRuntime(6719):关闭VM
03-18 14:06:23.178:W / dalvikvm(6719):主题ID = 1:螺纹未捕获的异常退出(组= 0x40a13300)
03-18 14:06:23.207:E / AndroidRuntime(6719):致命异常:主要
03-18 14:06:23.207:E / AndroidRuntime(6719):显示java.lang.NullPointerException
03-18 14:06:23.207:E / AndroidRuntime(6719):在me.mikey.my.games.galgjex.MikeyJSON<&初始化GT;(MikeyJSON.java:38)
03-18 14:06:23.207:E / AndroidRuntime(6719):在me.mikey.my.games.galgjex.JSONTester $ DownloadNewWords.onPostExecute(JSONTester.java:128)
03-18 14:06:23.207:E / AndroidRuntime(6719):在me.mikey.my.games.galgjex.JSONTester $ DownloadNewWords.onPostExecute(JSONTester.java:1)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.os.AsyncTask.finish(AsyncTask.java:631)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.os.AsyncTask.access $ 600(AsyncTask.java:177)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.os.Handler.dispatchMessage(Handler.java:99)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.os.Looper.loop(Looper.java:137)
03-18 14:06:23.207:E / AndroidRuntime(6719):在android.app.ActivityThread.main(ActivityThread.java:4745)
03-18 14:06:23.207:E / AndroidRuntime(6719):在java.lang.reflect.Method.invokeNative(本机方法)
03-18 14:06:23.207:E / AndroidRuntime(6719):在java.lang.reflect.Method.invoke(Method.java:511)
03-18 14:06:23.207:E / AndroidRuntime(6719):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)
03-18 14:06:23.207:E / AndroidRuntime(6719):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-18 14:06:23.207:E / AndroidRuntime(6719):在dalvik.system.NativeStart.main(本机方法)

噢,行38是:

  jsonArray = myObject.getJSONArray(galgjejson);


解决方案

myObject的是最有可能无效,因为你必须在你的类,然后私下内mikeyJSON。你应该尝试:

 私人的JSONObject myObject的;
私人JSONArray jsonArray;INT I;
公共MikeyJSON(字符串jsonString){
Log.i(JSON,jsonString:+ jsonString);
尝试{
    myObject的=新的JSONObject(jsonString);
    Log.i(JSON,myObject_Object:+ myObject.toString());
}赶上(JSONException E){
    // TODO自动生成catch块
    e.printStackTrace();
}}

望着那JSON我是pretty相信你可以使用字符串在构造函数,而不是一个JSONObject创建JSONArray。

编辑例子。

 私人JSONArray jsonArray;INT I;公共MikeyJSON(字符串jsonString){
尝试{
    jsonArray =新JSONArray(jsonString);
}赶上(JSONException E){
    // TODO自动生成catch块
    e.printStackTrace();
}}

Hello I keep getting NPE when I try to get an object from my jsonString. I tried alot of things even changed my json a coople of times but it's just not working. The HTTPResponse works fine and when I log "myObject" it gives the right object. But when I try to get the object in it it gives me a NPE. I tested the json and it is valid. I also tried to retrieve an array instead of an object but it also gives an NPE. Can someone tell me how to fix this.

I made a simple jsontester activity to test my 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;
        }
    }
}

}

And the jsonclass I use is:

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

Here is the json:

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

and here is the log:

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)

oh and line 38 is:

jsonArray = myObject.getJSONArray("galgjejson");
解决方案

myObject is most likely null since you have it in your class and then privately within mikeyJSON. You should probably try:

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

}

Looking at that JSON I am pretty sure you can create the JSONArray using the string in your constructor instead of a JSONObject.

Edited example.

private JSONArray jsonArray;

int i;

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

}

这篇关于试图从JSON字符串JSON数组或JSON对象时的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:50