讀取本地JSON文件並顯示

    程序功能:讀取本地JSON文件,並顯示到LsitView上,下面詳細介紹:html

 1 [
 2     {
 3       "operator":"admin1",
 4       "loginDate":"2012-10-20 10:28:10",
 5       "logoutDate":"2012-10-20 10:32:10"
 6     },
 7     {
 8       "operator":"admin2",
 9       "loginDate":"2012-10-22 10:20:10",
10       "logoutDate":"2012-10-22 10:32:10"
11     },
12     {
13       "operator":"admin3",
14      "loginDate":"2012-10-23 10:28:10",
15       "logoutDate":"2012-10-23 10:32:10"
16     },
17     {
18       "operator":"admin4",
19       "loginDate":"2012-10-20 10:28:10",
20       "logoutDate":"2012-10-20 10:32:10"
21     }
22 ]

      先準備內容如上的"json.txt"文件,放到項目的assets目錄下(此處能夠是本地SD卡只是讀取的方式有些異同)。首先要讀出json.txt的內容,要訪問assets下的資源,須要使用AssetManager類的open(filename)方法,文中省去(AssetManager assetManager = getAssets();)步驟,簡寫爲Context.getAssets().open(filename)。open方法返回一個輸入流,咱們即可以經過這個流來獲得json字符串。java

 1     /**
 2      * 讀取本地文件中JSON字符串
 3      * 
 4      * @param fileName
 5      * @return
 6      */
 7     private String getJson(String fileName) {
 8 
 9         StringBuilder stringBuilder = new StringBuilder();
10         try {
11             BufferedReader bf = new BufferedReader(new InputStreamReader(
12                     getAssets().open(fileName)));
13             String line;
14             while ((line = bf.readLine()) != null) {
15                 stringBuilder.append(line);
16             }
17         } catch (IOException e) {
18             e.printStackTrace();
19         }
20         return stringBuilder.toString();
21     }

      得到JSON字符串,咱們即可以解析,進而獲得對咱們有用的數據,Adnroid已經加入了org.json.*,因此我對json的操做也變得簡單起來,使用JSONArray array = new JSONArray(str) 就能把咱們剛剛獲得的JSON串傳化爲JSONArray,請注意觀察咱們的josn.txt的內容,其中包括了四組數據結構相同的數據,每一組數據當作一個JSONObject(包含了若干鍵值對,很像Map),而這些JSONObject便組成了一組JSONArray數組,因此咱們只要遍歷這個array就能夠獲得其中的全部JSONObject了,有了JSONObject就能夠經過Key得到對應的Value值了。android

 1     /**
 2      * 將JSON字符串轉化爲Adapter數據
 3      * 
 4      * @param str
 5      */
 6     private void setData(String str) {
 7         try {
 8             JSONArray array = new JSONArray(str);
 9             int len = array.length();
10             Map<String, String> map;
11             for (int i = 0; i < len; i++) {
12                 JSONObject object = array.getJSONObject(i);
13                 map = new HashMap<String, String>();
14                 map.put("operator", object.getString("operator"));
15                 map.put("loginDate", object.getString("loginDate"));
16                 map.put("logoutDate", object.getString("logoutDate"));
17                 data.add(map);
18             }
19         } catch (JSONException e) {
20             e.printStackTrace();
21         }
22     }

         填充完咱們的數據集合,就能夠放置到Adapter中,並顯示到LsitView中,下面給出完整代碼,json

json.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     android:orientation="vertical" >
 6 
 7     <ListView
 8         android:id="@+id/listView"
 9         android:layout_width="fill_parent"
10         android:layout_height="wrap_content" >
11     </ListView>
12 
13 </LinearLayout>
json_item.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent" >
 5 
 6     <TextView
 7         android:id="@+id/operator_tv"
 8         android:layout_width="fill_parent"
 9         android:layout_height="wrap_content"
10         android:layout_marginLeft="15dp" />
11 
12     <TextView
13         android:id="@+id/loginDate_tv"
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content"
16         android:layout_alignLeft="@id/operator_tv"
17         android:layout_below="@id/operator_tv" />
18 
19     <TextView
20         android:id="@+id/logoutDate_tv"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content"
23         android:layout_alignTop="@+id/loginDate_tv"
24         android:layout_marginLeft="15dp"
25         android:layout_toRightOf="@+id/loginDate_tv" />
26 
27 </RelativeLayout>
java代碼
  1 public class JSONTextActivity extends Activity {
  2 
  3     private ListView listView;
  4     private List<Map<String, String>> data;
  5     private final static String fileName = "json.txt";
  6     private ProgressDialog pd;
  7 
  8     @Override
  9     protected void onCreate(Bundle savedInstanceState) {
 10         super.onCreate(savedInstanceState);
 11         setContentView(R.layout.json);
 12         init();
 13         pd.show();
 14         new DataThread().start();
 15 
 16     }
 17 
 18     /**
 19      * 初始化
 20      */
 21     private void init() {
 22         listView = (ListView) findViewById(R.id.listView);
 23         data = new ArrayList<Map<String, String>>();
 24         pd = new ProgressDialog(this);
 25         pd.setMessage("數據加載中……");
 26 
 27     }
 28 
 29     /**
 30      * 加載數據線程
 31      */
 32     class DataThread extends Thread {
 33 
 34         @Override
 35         public void run() {
 36             String jsonStr = getJson(fileName);
 37             setData(jsonStr);
 38             dataHandler.sendMessage(dataHandler.obtainMessage());
 39         }
 40 
 41     }
 42 
 43     /**
 44      * 加載數據線程完成處理Handler
 45      */
 46     Handler dataHandler = new Handler() {
 47 
 48         public void handleMessage(android.os.Message msg) {
 49             if (pd != null) {
 50                 pd.dismiss();
 51             }
 52             SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
 53                     data, R.layout.json_item, new String[] { "operator",
 54                             "loginDate", "logoutDate" }, new int[] {
 55                             R.id.operator_tv, R.id.loginDate_tv,
 56                             R.id.logoutDate_tv });
 57             listView.setAdapter(adapter);
 58         }
 59     };
 60 
 61     /**
 62      * 讀取本地文件中JSON字符串
 63      * 
 64      * @param fileName
 65      * @return
 66      */
 67     private String getJson(String fileName) {
 68 
 69         StringBuilder stringBuilder = new StringBuilder();
 70         try {
 71             BufferedReader bf = new BufferedReader(new InputStreamReader(
 72                     getAssets().open(fileName)));
 73             String line;
 74             while ((line = bf.readLine()) != null) {
 75                 stringBuilder.append(line);
 76             }
 77         } catch (IOException e) {
 78             e.printStackTrace();
 79         }
 80         return stringBuilder.toString();
 81     }
 82 
 83     /**
 84      * 將JSON字符串轉化爲Adapter數據
 85      * 
 86      * @param str
 87      */
 88     private void setData(String str) {
 89         try {
 90             JSONArray array = new JSONArray(str);
 91             int len = array.length();
 92             Map<String, String> map;
 93             for (int i = 0; i < len; i++) {
 94                 JSONObject object = array.getJSONObject(i);
 95                 map = new HashMap<String, String>();
 96                 map.put("operator", object.getString("operator"));
 97                 map.put("loginDate", object.getString("loginDate"));
 98                 map.put("logoutDate", object.getString("logoutDate"));
 99                 data.add(map);
100             }
101         } catch (JSONException e) {
102             e.printStackTrace();
103         }
104     }
105 }

運行效果以下:數組

       

 

   

轉載於:https://www.cnblogs.com/liutianyi/archive/2012/09/24/2700176.html數據結構