【发布时间】:2013-05-11 11:50:03
【问题描述】:
我知道这是一个非常常见的问题,我在 SO 中发现了很多帖子。 我的代码如下,我看不出 json 数组返回 null 的原因。有人可以帮我检查一下吗?我不遗余力! :(
JsonArray jsonArr = JSONfunctions.getJSONfromURL(url);
try {
if (jsonArr != null) {
for (int i = 0; i < jsonArr.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObj = jsonArr.getJSONObject(i);
map.put(TAG_CODE, jsonObj.getString("Code"));
map.put(TAG_DISPLAY_NAME, jsonObj.getString("UserName"));
map.put(TAG_PROGRAM_NAME, jsonObj.getString("Password"));
mylist.add(map);
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
result = sb.toString();
// Result is always returning me an array.(not null)
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + result);
}
try {
jArray = new JSONArray(result);
// Goes into the catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("log_tag", "Error parsing result " + result);
}
return jArray;
}
}
【问题讨论】:
-
你把这段代码保存在哪里,是使用单独的线程还是 AsyncTask?
-
在单独的类文件中,但不在 Aysnc 任务中。它似乎在某个时候可以工作。 :(
-
它将适用于较旧的 android 版本(3.0 之前)。您必须在 AsyncTask 中移动它
-
错误信息是什么?我的意思是当它进入 catch 块时。
-
服务器返回的不是 JSONArray 而是 JSONOBject。您应该将 jArray 的类型从 JSONArray 更改为 JSONObject
标签: android json parsing arrays