2013-01-12 111 views
0

我有以下的(多了,但它只是一些它)在我的項目在原始文件夾中的JSON文件的代碼。顯示信息 - 安卓

{ 
"Monday": [ 
    { 
     "time": "09:15", 
     "class": "Nature", 
     "room": "AL32" 
    }, 
    { 
     "time": "10:15", 
     "class": "Nature", 
     "room": "AL32" 
    } 
], 
"Tuesday": [ 
    { 
     "time": "12:15", 
     "class": "Maths", 
     "room": "AL20" 
    }, 
    { 
     "time": "13:15", 
     "class": "Englsh", 
     "room": "AG22" 
    } 
]....etc 

} 

我希望它顯示像

Time|Class|Room 
Monday 
09:15|Nature|AL32 
10:15|Nature|AL32 
Tuesday 
12:15|Maths|AL20 
13:15|English|AG22 
etc etc 

我做了什麼(到目前爲止),在與 的BufferedReader jsonReader =新的BufferedReader(新的InputStreamReader(這在JSON文件中的信息讀取。 。getResources()openRawResource(R.raw.localjsonfile)));

然後我可以在文件中打印出來的一切(在logcat中)與

String readLine = null; 
// While the BufferedReader readLine is not null 
while ((readLine = jsonReader.readLine()) != null) 
{ 
    System.out.println(readLine); 
} 

,但我不知道從哪裏裏去。我想我星期一在一個名爲monday的數組/對象中存儲任何東西(星期二在一個數組/對象中稱爲星期二等),然後打印出數組/對象中的值,並將它們放入我擁有的TextView字段中我有三個文本視圖,分別稱爲android:id =「@ + id/time」,android:id =「@ + id/class和android:id =」@ + id/room「),然後textviews會重新顯示到屏幕上根據需要,

我只有開始學習Android和Java和我一無所知JSON,所以我堅持就如何繼續走下去。

回答

0

試試這個代碼從一排文件夾,並解析獲得JSON 。

//Get Data From Text Resource File Contains Json Data. 

     InputStream inputStream = getResources().openRawResource(R.raw.localjsonfile); 

     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

     int ctr; 
     try { 
      ctr = inputStream.read(); 
      while (ctr != -1) { 
       byteArrayOutputStream.write(ctr); 
       ctr = inputStream.read(); 
      } 
      inputStream.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Log.v("Text Data", byteArrayOutputStream.toString()); 
     try { 

      // Parse the data into jsonobject to get original data in form of json. 
      JSONObject jObject = new JSONObject(
        byteArrayOutputStream.toString()); 

      JSONArray jArray = jObject.getJSONArray("Monday"); 
      String time=""; 
      String class =""; 
      String room =""; 

      ArrayList<String[]> data = new ArrayList<String[]>(); 
      for (int i = 0; i < jArray.length(); i++) { 
       time= jArray.getJSONObject(i).getString("time"); 
       class= jArray.getJSONObject(i).getString("class"); 
       room= jArray.getJSONObject(i).getString("room"); 

       data.add(new String[] {time, class,room}); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

看看這個library與JSON解析, 有助於爲JSON解析的更多示例讀this article

+0

謝謝,上面的代碼的工作,但我不得不改變「jObjectResult」到「jObject」和類模塊,否則有錯誤。我已經通過使用\t \t \t的TextView TV0 =(TextView的)findViewById(R.id.time)得到的時間,類和房間打印出到屏幕上; tv0.setText(time); 但是這隻能打印一次'時間'。我不知道如何讓它打印出不止一行。我想我以某種方式爲數據陣列中的每一行設置它,一行返回到屏幕。 – Mary