2013-01-12 54 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