在Android中存储嵌套静态数据(数组)的最佳方法?

时间:2014-08-22 07:45:20

标签: android

所以我有数据,例如:

  

1个主题将在2个教室进行,每个教室有不同的副主题   从上午9点到下午12点。

如果采用JSON格式,它将如下所示:

{
    "Mathematic": [
        {
            "time": [
                {
                    "startTime": "09.00",
                    "endTime": "10.00",
                    "class": [
                        {
                            "subtopic": "What is Calculus?",
                            "roomName": "Class A"
                        },
                        {
                            "subtopic": "Basic of Calculus",
                            "roomName": "Class B"
                        }
                    ]
                }
            ]
        }
    ]
}

如果我将json文件放在assets文件夹中,我相信JSON解析器需要一些时间来解析它。

我还想把它放在arrays.xml

<array name="testArray">
    <item>first</item>
    <item>second</item>
    <item>
        <array name="testArrayNested">
            <item>
                first nested
            </item>
            <item>
                second nested
            </item>
        </array>
    </item>
    <item>fourth</item>
    <item>fifth</item>
</array>

我不知道如何获取嵌套数组,这是我的代码:

String [] test = getResources().getStringArray(R.array.testArray);
for(int i = 0; i < test.length; i++)
    System.out.println("test: " + test[i]);

输出:

test: first
test: second
test:    first nested   second nested   
test: fourth
test: fifth

存储嵌套静态数据的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

为了满足您的JSON,将需要这种类型的结构。

class Lecture { //Mathematic
  String name;
  List<Timetable> timetables;
}

class Timetable { //time

  Time start;
  Time end;
  List<Lesson> classes;
}


class Lesson { //class
   ClassRoom room;
   Topic     topic;
}

class Topic { 
  String name;

}

class ClassRoom {
  String name;
}

但是如果你能改变那个json

我建议

class Subject {
    String topic;
}

class Lesson {
    Subject subject;
    String topic;
}

class Classroom {
    String name;
}

class ClassroomLesson {
    Lesson lesson;
    Classroom classroom;
    String hour;
}

class Schedule {
    List<ClassroomLesson> lessons = new ArrayList<>();
}


{
  "lessons": [
    {
      "lesson": {
        "subject": {
          "topic": "Mathematics"
        },
        "topic": "Lesson 1"
      },
      "classroom": {
        "name": "Classroom 1"
      },
      "hour": "09:00"
    },
    {
      "lesson": {
        "subject": {
          "topic": "Mathematics"
        },
        "topic": "Lesson 2"
      },
      "classroom": {
        "name": "Classroom 2"
      },
      "hour": "10:00"
    }
  ]
}