How can I more efficiently find all of targeted objects in JSON File?

Viewed 28

I have a JSON file that is serving as data storage for my application:

{
  "users": {
    "instructors": [
      {
        "id": 1234,
        "password": "hello1234",
        "name": "Teacher 1",
        "listOfCourses": [
          {
            "id": 3622,
            "name": "CS 3622",
            "studentsEnrolled": [
              {
                "id": 1002,
                "name": "Student 1",
                "dateOfBirth": "00/11/2222"
              },
              {
                "id": 1002,
                "name": "Student 2",
                "dateOfBirth": "00/11/2222"
              }
            ]
          },
          {
            "id": 4306,
            "name": "CS 4306",
            "studentsEnrolled": [
              {
                "id": 1002,
                "name": "Student 3",
                "dateOfBirth": "33/44/55"
              },
              {
                "id": 1002,
                "name": "Jay Wright",
                "dateOfBirth": "33/44/5555"
              }
            ]
          }
        ]
      }
    ],
    "admin": [
      {
        "userId": 12345,
        "userPassword": "hello12345",
        "name": "Admin 1"
      },
      {
        "userId": 123456,
        "userPassword": "hello12345",
        "name": "Admin 2"
      }
    ]
  }
}

The above file is passed into a Java.io.File object. I am trying to find a more time efficient manner of retrieving all the course objects from the JSON file. I am currently using Jackson and have implemented the below method:

public List<Course> retrieveAll() throws IOException {

        if (this.allCourses != null) {
            return this.allCourses;
        }

        List<Course> listOfAllCourses = new ArrayList<>();
        JsonNode instructors = root.get("users").get("instructors");

        ArrayNode arrayNode = (ArrayNode) instructors;
        Iterator<JsonNode> iter = arrayNode.iterator();

        while (iter.hasNext()) {
            JsonNode currentInstructor = iter.next();
            ArrayNode arrayNodeOfCourses = (ArrayNode) currentInstructor.get("listOfCourses");

            Iterator<JsonNode> iter2 = arrayNodeOfCourses.iterator();

            while (iter2.hasNext()) {
                Course currentCourse = objectMapper.treeToValue(iter2.next(), Course.class);
                currentCourse.setCourseInstructor(objectMapper.treeToValue(currentInstructor, Instructor.class));

                listOfAllCourses.add(currentCourse);
            }
        }
        this.allCourses = listOfAllCourses;
        return listOfAllCourses;
    }

However, I am looking for a more efficient way of doing this hopefully without nested loops as that can give the method a time efficiency of O(nm).

0 Answers
Related