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