显示从json文件读入的信息 - android

时间:2013-01-12 19:53:58

标签: android json

我的项目中的raw文件夹中的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

我所做的(到目前为止)是,阅读json文件中的信息 BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.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的数组/对象中存储任何东西(周二在一个名为tuesday等的数组/对象中)然后打印出数组/对象中的值并将它们放在我拥有的TextView字段中(我有三个文本视图叫做android:id =“@ + id / time”,android:id =“@ + id / class and android:id =”@ + id / room“)然后将textviews重新打印到屏幕上根据需要。

我刚刚开始学习android和java,我对json一无所知,所以我不知道如何继续学习。

1 个答案:

答案 0 :(得分: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

相关问题