這是一個小練習,要求解析一個提供的json文件。並將其中的id,title值獲取,以ListView形式展現出來。(開發工具是android studio)java
首先我想到的是先把json文件內容讀進一個String類型的變量中去保存,而後再對字符串進行解析。Id和title能夠看作爲一組數據,而後整個文件有不少組數據,因此建立了android
1 ArrayList<HashMap> ArrayList=new ArrayList<>(); json
list中保存全部條數據,須要時再獲取。因此,我用了Map,固然這只是針對實現功能來說。後來我對此進行了改進,決定用JavaBean來存儲數據。JavaBean比Map在此的好處是,我能夠清楚的知道每條數據由哪些部分構成,這在數據量大的時候比較有好處。數組
要把json文件讀進來,文件放在assets目錄下。文件讀取的工做單獨在一個.java文件裏面進行,在activity裏面使用安全
OpenFile openFile=new OpenFile(); String JsonContext=openFile.oFile("json.txt",this);
"json.txt"爲文件路徑,this表明傳遞當前context,若是不傳遞參數this,在一個非activity的java裏面獲取assets資源文件比較麻煩,因此此處傳了個context對象。(至少我如今沒搜到如何在一個非activity的java裏面打開assets資源文件)。多線程
這是讀取文件的j代碼,單獨在一個java裏面:ide
public class OpenFile extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public String oFile(String Path, Context context){ InputStream inputStream = null; try { inputStream = context.getAssets().open(Path); } catch (IOException e) { e.printStackTrace(); } InputStreamReader inputStreamReader=new InputStreamReader(inputStream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String JsonContext="";/*存放JSON數據的字符串變量*/ String tempString; try { while((tempString =bufferedReader.readLine()) != null){ JsonContext += tempString; } } catch (IOException e) { e.printStackTrace(); } try { inputStream.close(); inputStreamReader.close();/*及時關閉流*/ } catch (IOException e) { e.printStackTrace(); } return JsonContext; } }
小練習一個,並沒開多線程來讀文件。工具
inputStream = context.getAssets().open(Path);
關於在android studio裏面讀取assets資源文件,可使用上面的方法來進行。重點是解析json內容。上面用Jsoncontext獲取了文件的內容,下面要進行解析:學習
JSONObject jsonObject_=new JSONObject(JsonContext);/*整個內容是一個對象*/ JSONArray jsonArray=jsonObject_.getJSONArray("stories");/*對象裏面是一個個數組、屬性,可用KEY獲取某數組*/ int size = jsonArray.length();/*數組裏又是一個個對象,遍歷數組,利用KEY獲取目標值*/for(int i = 0; i < size; i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); NewsBean newsBean=new NewsBean(); String title=(String) jsonObject.get("title"); String id =jsonObject.get("id").toString(); newsBean.setId(id); newsBean.setTitle(title); newsBeanArrayList.add(newsBean);}
註釋裏面也已經寫了一些,先把整個內容存爲一個JSONObject ,這個對象裏面有普通的KEY:VALUE,也有KEY:ARRAY,顯然咱們須要的東西在KEY:ARRAY裏面,咱們利用KEY也即stories來獲取該數組,數組裏面有好多對象,利用for循環遍歷,從每一個對象中獲取咱們想要的數據。下面是我所解析的json原文件:開發工具
{ "date": "20161228", "stories": [ { "images": [ "http://pic2.zhimg.com/7ee47bcb49143225aeb8a8a370e4d709.jpg" ], "type": 0, "id": 9094984, "ga_prefix": "122822", "title": "小事 · 即便身爲醫生" }, { "images": [ "http://pic1.zhimg.com/5bd9eabd8c53e171798fee13d42673fc.jpg" ], "type": 0, "id": 9103638, "ga_prefix": "122821", "title": "春節將至,我也想要個這樣的形婚對象" }, { "images": [ "http://pic3.zhimg.com/772cf1999171db2992b32ae71dc071de.jpg" ], "type": 0, "id": 9104614, "ga_prefix": "122820", "title": "投行中各類崗位的職能和級別都是什麼?" }, { "images": [ "http://pic2.zhimg.com/962ab131caef4de67f9a608aa1adc369.jpg" ], "type": 0, "id": 9101614, "ga_prefix": "122819", "title": "5000 塊買不起袋大米,韓「圓」面額幹嗎搞還麼大?" }, { "images": [ "http://pic2.zhimg.com/e1bf9f3b4bb33e6c6659fe5fb3aa08fd.jpg" ], "type": 0, "id": 9104329, "ga_prefix": "122818", "title": "卡麗 · 費希爾,咱們的公主,走了" }, { "images": [ "http://pic4.zhimg.com/6aba8539df59fb3dbadeaedbfaf54b4b.jpg" ], "type": 0, "id": 9104500, "ga_prefix": "122817", "title": "知乎好問題 · 如何學習單板滑雪?" }, { "images": [ "http://pic2.zhimg.com/193971026e5dc269cc03fb0b0f22483d.jpg" ], "type": 0, "id": 9103736, "ga_prefix": "122816", "title": "爲何美國本土皮卡那麼火?由於雞" }, { "title": "一個沒有方向的巨人摔倒了,這是 Twitter 背後的故事", "ga_prefix": "122815", "images": [ "http://pic3.zhimg.com/b0e61dd89b0421eaf9c990b6bd10e696.jpg" ], "multipic": true, "type": 0, "id": 9103202 }, { "title": "新年到,殺年豬,鮮香爽口的酸菜白肉鍋也上桌了", "ga_prefix": "122815", "images": [ "http://pic2.zhimg.com/b9045eccb23e72ce32a55b4895fc2539.jpg" ], "multipic": true, "type": 0, "id": 9095420 }, { "images": [ "http://pic1.zhimg.com/85ef349a9ced422f54029cb08106c774.jpg" ], "type": 0, "id": 9102480, "ga_prefix": "122813", "title": "孕婦呼吸被污染的空氣,孩子也會受影響,這是證據" }, { "images": [ "http://pic3.zhimg.com/b4f604f118572634b1db38700c9a8c1a.jpg" ], "type": 0, "id": 9096964, "ga_prefix": "122812", "title": "大誤 · 你看這有一個洞" }, { "images": [ "http://pic3.zhimg.com/573b48c15c83a4acc32bbda0a2ad8b72.jpg" ], "type": 0, "id": 9103208, "ga_prefix": "122811", "title": "據說手機都會爆炸,電動汽車那麼多的電池真的安全嗎?" }, { "title": "自由隨性,清醒而瘋狂,就愛「不正常」的淺野忠信", "ga_prefix": "122810", "images": [ "http://pic1.zhimg.com/58b11e74cc78c299766f956023c2c7b0.jpg" ], "multipic": true, "type": 0, "id": 9100776 }, { "images": [ "http://pic4.zhimg.com/7561fd80ca4122261c3b34ab31df118f.jpg" ], "type": 0, "id": 9083880, "ga_prefix": "122809", "title": "用來給孩子爬來爬去的墊子,買以前可得好好挑選" }, { "images": [ "http://pic1.zhimg.com/3d81afc4f9738fafbfee0a357c381e90.jpg" ], "type": 0, "id": 9087927, "ga_prefix": "122808", "title": "打算年後跳槽,如今就準備一份漂亮的簡歷吧" }, { "images": [ "http://pic4.zhimg.com/c6df92901b4aa48e6017584454481b67.jpg" ], "type": 0, "id": 9101814, "ga_prefix": "122807", "title": "一瓶一塊,三瓶兩塊五,該怎麼買?" }, { "images": [ "http://pic1.zhimg.com/11b50a06a8ae68bf32057e40b8c9b588.jpg" ], "type": 0, "id": 9086246, "ga_prefix": "122807", "title": "法律意義上,宿舍算「住宅」嗎?" }, { "images": [ "http://pic3.zhimg.com/7642324a20c278c69d0c15b0cbda5be6.jpg" ], "type": 0, "id": 9101810, "ga_prefix": "122807", "title": "2016 年度盤點 · 奧巴馬,全球最有名的科技宅" }, { "images": [ "http://pic3.zhimg.com/785abaf0cc4f4b26763a6c97ebd28626.jpg" ], "type": 0, "id": 9102445, "ga_prefix": "122806", "title": "瞎扯 · 如何正確地吐槽" } ],}
關於javabean的寫法,非常老套:
public class NewsBean{ private String id; private String title; public String getId(){ return id; } public void setId( String newId){ this.id=newId; } public String getTitle(){ return title; } public void setTitle(String newTitle){ this.title=newTitle; } }
這是MyAdapter的書寫:
public class MyAdapter extends BaseAdapter { private ArrayList<NewsBean> newsBeanArrayList; private Context context; private LayoutInflater mInflater=null; public MyAdapter(ArrayList<NewsBean> newsBeanArrayList,Context mContext){ this.newsBeanArrayList=newsBeanArrayList; this.context=mContext; } @Override public int getCount() { return this.newsBeanArrayList.size(); } @Override public Object getItem(int position) { return this.newsBeanArrayList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { NewsBean newsBean=newsBeanArrayList.get(position);//把newsBeanArrayList中特定位置的NewsBean對象得到 if (convertView==null){ convertView=mInflater.from(context).inflate(R.layout.user,null); } TextView tv_1=(TextView) convertView.findViewById(R.id.key); TextView tv_2=(TextView) convertView.findViewById(R.id.value); String id=; String title=newsBean.getTitle(); tv_1.setText(id); tv_2.setText(title); convertView.setTag(newsBean); return convertView; } }
主要是寫好那四個方法,前三個基本沒問題,主要是寫getView,弄明白裏面的三個參數的做用。這是最簡單的一種寫法,能夠在此基礎上進行不少的優化。
下面是Activity的代碼:
public class Main2Activity extends ListActivity { private final String TAG="Main2Activity"; static int a=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); final ArrayList<NewsBean> newsBeanArrayList=new ArrayList<>(); /*流操做讀JSON文件,並存到JsonContext中*/ OpenFile openFile=new OpenFile(); String JsonContext=openFile.oFile("json.txt",this); try { JSONObject jsonObject_=new JSONObject(JsonContext);/*整個內容是一個對象*/ JSONArray jsonArray=jsonObject_.getJSONArray("stories");/*對象裏面是一個個數組、屬性,可用KEY獲取某數組*/ int size = jsonArray.length();/*數組裏又是一個個對象,遍歷數組,利用KEY獲取目標值*/ Log.i(TAG,"size"+size); for(int i = 0; i < size; i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); NewsBean newsBean=new NewsBean(); String title=(String) jsonObject.get("title"); String id =jsonObject.get("id").toString(); newsBean.setId(id); newsBean.setTitle(title); newsBeanArrayList.add(newsBean); } JSONArray jsonArray2=jsonObject_.getJSONArray("top_stories"); size = jsonArray2.length(); Log.i(TAG,"size"+size); for(int i = 0; i < size; i++){ JSONObject jsonObject = jsonArray2.getJSONObject(i); NewsBean newsBean=new NewsBean(); String title=(String) jsonObject.get("title"); String id =jsonObject.get("id").toString(); newsBean.setId(id); newsBean.setTitle(title); newsBeanArrayList.add(newsBean); } } catch (JSONException e) { e.printStackTrace(); } MyAdapter myAdapter=new MyAdapter(newsBeanArrayList,this);//建立適配器,傳參數爲NewsBean集合,Context->this, setListAdapter(myAdapter); } }
整個程序就是MainActivity 裏面點擊按鈕進入Main2Activity,而後建立List集合,調用OpenFile打開文件,返回String類型的值賦值給JsonContext,對 JsonContext進行一步步解析,將解析獲得的結果存到一個個的NewsBean對象之中,並把全部的NewsBean添加至List集合中去。最後BaseAdapter的書寫爲ListView添加適配器。