我正在尝试从http://inspirontrance.com/app.php解析 JSON 数组,但它不起作用。我相信我的代码可能存在问题,或者 url 只是重定向到 defaultHttpClient 不支持的另一个 url。
看我的代码,
Android 解析活动类
public class AndroidJSONParsingActivity extends ListActivity {
private static String url = "http://www.inspirontrance.com/app";
private static final String TAG_UPLOADS = "uploads";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_DATE = "date";
private static final String TAG_UPLOAD_NO = "0";
JSONArray uploads = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> uploads_list = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
uploads = json.getJSONArray(TAG_UPLOADS);
for (int i = 0; i < uploads.length(); i++) {
JSONObject c = uploads.getJSONObject(i);
JSONObject upload_no = c.getJSONObject(TAG_UPLOAD_NO);
String name = upload_no.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
uploads_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, uploads_list,
R.layout.list_item, new String[] { TAG_NAME },
new int[] { R.id.name });
setListAdapter(adapter);
}
}
JSON解析器类
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}