【发布时间】:2013-05-24 12:57:54
【问题描述】:
我是这个 android 编程的新手,我在解析 JSON 时遇到了问题。 这是我要解析 Billers 并查看到 ListView 的 JSON URL。我有一些我已经使用并成功提取我想要的值的代码。问题是我不能或者准确地说我在解析 JSON 数组时遇到了问题。 这是我用于解析 JSON 数组的代码:
public class BillersJsonParser {
String mUrl;
public BillersJsonParser(String url){
this.mUrl = url;
}
public BillersModel getCategories(){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mUrl);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
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();
String result = sb.toString();
return parse(result);
} catch (JSONException e) {
return null;
} catch (ClientProtocolException e) {
return null;
} catch (IOException e) {
return null;
}
}
private BillersModel parse(String result) throws JSONException{
BillersModel billerList = new BillersModel();
JSONObject jObject = new JSONObject(result);
JSONArray bList = jObject.getJSONArray("billers");
Log.e("BJSONParser 2nd Lvl: ", bList.toString());
int length = bList.length();
for (int i = 0; i < length; i++){
billerList.setID(bList.getJSONObject(i).getString("bid"));
billerList.setName(bList.getJSONObject(i).getString("name"));
billerList.setStatus(bList.getJSONObject(i).getString("status"));
billerList.setDateAdded(bList.getJSONObject(i).getString("date_added"));
}
return billerList;
}
}
每次我运行这段代码时都会出现 Null 异常错误,我无法弄清楚。我怀疑当eclipse尝试运行这部分代码JSONArray bList = jObject.getJSONArray("billers");时错误开始了。任何帮助将不胜感激。
【问题讨论】:
-
json 是 utf-8,不是 iso
-
如果您使用的是 Eclipse,您应该有一个 Stacktrace,您甚至可以在其中单击以转到引发异常的行。至少设置 StackTrace 和行号会有所帮助...
-
不要丢弃你的异常。 e.printstacktrace 他们
-
catch (JSONException e) { return null; }这样的代码是非常糟糕的做法
标签: java android json android-listview