读取本地JSON文件并显示

来源:互联网 发布:航天开票软件如何升级 编辑:程序博客网 时间:2024/05/17 23:32
程序功能:读取本地JSON文件,并显示到LsitView上,下面详细介绍:
复制代码
 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字符串。

复制代码
 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值了。

复制代码
 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中,下面给出完整代码,

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码
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     <TextView13         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     <TextView20         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 }
复制代码

运行效果如下:

       


原创粉丝点击