检索JSON对象时出现空指针异常

时间:2012-06-17 08:16:50

标签: android json

我是JSON的新手。我正在使用http://pnrapi.appspot.com/来获取使用JSON的特定列车的状态。但是在尝试解析收到的对象时,我总是得到一个空指针异常。请帮忙。

这是我的代码。

public class PNRStatusActivity extends Activity {
    private static final String TAG_CONTACTS = "contacts";
    static InputStream is = null;
    JSONObject jObj = null;
    static String json = "";
    JSONArray contacts = null;
    private static String url = "http://pnrapi.appspot.com/4051234567";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Creating JSON Parser instance
        JSONObject jon=getJSONFromUrl(url);

        try {
            // Storing each json item in variable
            String id = jon.getString("status");
            Toast.makeText(getApplicationContext(), id, Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //function to get JSON Object
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

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

3 个答案:

答案 0 :(得分:3)

您的代码中存在许多问题,但并不一定都与您的NullPointerException直接相关......

  1. getJSONFromUrl方法中使用HttpPost时,您实际上似乎没有发布任何内容。请改用HttpGet

  2. 从响应中读取JSON字符串时,使用getContentLength()的{​​{1}}方法创建一个字节数组,例如(示例)......

    HttpEntity,只需将byte[] buffer = new byte[contentLength]视为......

    InputStream。您将需要在整个过程中进行错误检查。在你的情况下,你试图逐行读取一个字符串,并在每一行附加“n”。首先,您不需要以这种方式读取JSON字符串,如果您实际上打算附加换行符(任何时候在任何Java代码中),它应该是“\ n”。

  3. 要将您的字节数组转换为可用于JSON解析的字符串,您只需执行以下操作即可...

    inStream.read(buffer)

  4. 如果您真的可以避免,请不要指定String jsonString = new String(buffer, "UTF-8")编码。

  5. 当您使用iso-8859-1 Toast方法创建Activity时,使用onCreate(...)。除非您确定何时何地使用它,否则请勿使用应用程序上下文。在getApplicationContext()代码的主体中,您可以在创建Activity's时使用this Context

  6. 正如其他人所提到的那样,请确保在可能发生的任何地方检查Toast返回。如果方法中发生异常且返回为null,请确保调用该方法的代码检查null

答案 1 :(得分:1)

仔细查看您的代码

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

        // return JSON String
        return jObj;

在上面的例子中,如果你得到任何JSONException,那么你将返回未初始化的jObj,简而言之,你将返回null jObj。

所以你通过检查返回的对象是否为空来处理这种情况。

将您的代码更改为以下

if (jon != null)
{
    String id = jon.getString("status");
    Toast.makeText(getApplicationContext(), id, Toast.LENGTH_LONG).show();
}

答案 2 :(得分:1)

使用获取代替 getString

try {
    JSONObject jsona=new JSONObject("{'status': 'INVALID', 'data': 'No results'}");
    String id = (String)jsona.get("status");
    Toast.makeText(DfgdgdfgdfActivity.this, id, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

编辑:

使用

while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

而不是

while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
相关问题