我是 JSON 新手。我在用http://pnrapi.appspot.com/ 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;
}
}
您的代码中存在很多问题,尽管不一定所有问题都与您的代码直接相关NullPointerException
...
In your getJSONFromUrl
你正在使用的方法HttpPost
当你看起来并没有真正发布任何内容时。使用HttpGet
反而。
-
从响应中读取 JSON 字符串时,请使用getContentLength()
的方法HttpEntity
创建一个字节数组,例如(示例)...
byte[] buffer = new byte[contentLength]
并简单地阅读InputStream
as...
inStream.read(buffer)
。当然,您需要一路进行错误检查。在您的情况下,您尝试逐行读取字符串并将“n”附加到每行。首先,您不需要以这种方式读取 JSON 字符串,如果您实际上打算附加换行符(在任何 Java 代码中的任何时间),它应该是“\n”。
-
要将字节数组转换为可用于 JSON 解析的字符串,只需执行以下操作...
String jsonString = new String(buffer, "UTF-8")
从不指定iso-8859-1
如果你真的可以避免的话,可以对任何东西进行编码。
当您创建您的Toast
在你的Activity
onCreate(...)
方法,你使用getApplicationContext()
。除非您确实确定应该在何时何地使用应用程序上下文,否则不要使用它。在主体中Activity's
您可以简单地使用代码this
为了Context
当创建一个Toast
.
正如其他人提到的,请确保检查null
返回任何可能发生的地方。如果方法中发生异常并且返回的是null
确保调用该方法的任何代码都会检查null
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)