想要在Android當中從URL取得JSON格式,大概需要執行以下步驟:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />2. 使用HttpClient與HttpResponse方法Parse URL並取得JSON String。
3. 建立JSONObject與JSONArray來處理JSON String。
4. 從JSONObject與JSONArray取出你要的資料。
請記得一定要使用AsyncTask來處理,因為這是UI Thread。
以下為具體程式碼:
其中我們要取得的JSON格式來源:http://hmkcode.appspot.com/rest/controller/get.json
{"articleList": [{ "title":"Android Internet Connection Using HTTP GET (HttpClient)", "url":"http://hmkcode.com/android-internet-connection-using-http-get-httpclient/", "categories":["Android"], "tags":["android","httpclient","internet"] }, { "title":" Android | Taking Photos with Android Camera ", "url":"http://hmkcode.com/android-camera-taking-photos-camera/", "categories":["Android"], "tags":["android","camera"] }] }
java程式中的AsyncTask核心部份:
private class HttpAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { return GET(urls[0]); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { try { JSONObject json = new JSONObject(result); String str = ""; JSONArray articles = json.getJSONArray("articleList"); str += "articles length = "+json.getJSONArray("articleList").length(); str += "\n--------\n"; str += "names: "+articles.getJSONObject(0).names(); str += "\n--------\n"; str += "url: "+articles.getJSONObject(0).getString("url");
} catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String GET(String url){ InputStream inputStream = null; String result = ""; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } return result; } private String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } }
其使用方式很簡單,在你的主程式當中加入以下調用:
new HttpAsyncTask().execute("http://hmkcode.appspot.com/rest/controller/get.json");
上述當中以及實現了從URL中取得JSON格式,並放至str中,我這裡是沒有將他印出,而你當然可以使用Log印出看看str,或者是你想顯示在圖形界面,隨便你。
Reference:
- http://hmkcode.com/android-parsing-json-data/
- http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
你好
回覆刪除如何將asynctask中的JSONObject傳回MainActivity呢?
謝謝
最簡單方法是宣告JSONObject 為全域變數,然後在asynctask裡面的onPostExecute取得你要的JSON資料即可。
回覆刪除