也可以用過HttpClient ,AsyncTask實現此功能,此處就不說啦。
廢話不多少直接上代碼了
-------------------------------分割線----------------------------------------
activity_main.xml(只有一個簡單TextView,用於展示獲取JSON後更新其Text)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zb.json_text.MainActivity"
tools:ignore="MergeRootFrame"
android:background="#f1f1f1"
android:orientation="vertical" >
<TextView
android:id="@+id/textview_01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="出發吧,總會到達..."/>
</LinearLayout>
MainActivity.java
package com.zb.json_text;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textview_01;
private List<Map<String, String>> slist;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
Map<String, String> map = slist.get(2); // 例子而已,直接獲取下標爲2的值了,可以通過循環將list的值取出
textview_01.setText(map.get("title"));//在handler中更新UI
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String path = "http://xxxxxxxxxxxxxxxxxxx.html?format=json&size=5";
textview_01 = (TextView) findViewById(R.id.textview_01);
new Thread() {//創建子線程進行網絡訪問的操作
public void run() {
try {
slist = getJSONObject(path);
handler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 獲取網絡中的JSON數據
* @param path
* @return
* @throws Exception
*/
public static List<Map<String, String>> getJSONObject(String path)
throws Exception {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
URL url = new URL(path);
// 利用HttpURLConnection對象,我們可以從網頁中獲取網頁數據
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 單位爲毫秒,設置超時時間爲5秒
conn.setConnectTimeout(15 * 1000);
// HttpURLConnection對象是通過HTTP協議請求path路徑的,所以需要設置請求方式,可以不設置,因爲默認爲get
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {// 判斷請求碼是否200,否則爲失敗
InputStream is = conn.getInputStream(); // 獲取輸入流
byte[] data = readStream(is); // 把輸入流轉換成字符串組
String json = new String(data); // 把字符串組轉換成字符串
// 數據形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"張三"},{"id":2,"name":"李斯"}]}
JSONObject jsonObject = new JSONObject(json); // 返回的數據形式是一個Object類型,所以可以直接轉換成一個Object
int total = jsonObject.getInt("count");
String keywords = jsonObject.getString("keywords");
// 裏面有一個數組數據,可以用getJSONArray獲取數組
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 1; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i); // 得到每個對象
int id = item.getInt("id");
String title = item.getString("title");
String description = item.getString("description");
int time = item.getInt("time");
map = new HashMap<String, String>();
map.put("id", id + "");
map.put("title", title);
map.put("description", description);
map.put("time", time + "");
list.add(map);
}
}
return list;
}
private static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();
return bout.toByteArray();
}
}
源碼地址:http://download.csdn.net/detail/u011732740/8854953