0

What I've already done is copied the data from an API into its own JSON file, Courses.json using filewriter and the package com.google.gson. Overall, the data I need to retrieve is user_id under enrollments.

A shortened and redacted version of Courses.json is as such:

[
  {
    "access_restricted_by_date":true,
    "id":3155
  },
  {
    "access_restricted_by_date":true,
    "id":4604
  },
  {
    "access_restricted_by_date":true,
    "id":4655
  },
  {
    "root_account_id":1,
    "storage_quota_mb":50000,
    "template":false,
    "end_at":null,
    "public_syllabus_to_auth":false,
    "public_syllabus":false,
    "created_at":"2022-08-11T18:00:41Z",
    "start_at":null,
    "enrollment_term_id":180,
    "uuid":"MC24SbWdGDjeKTalLT5T5V41Foh0jD4EybOFG8xY",
    "course_code":"Study Hall",
    "course_color":null,
    "grading_standard_id":null,
    "workflow_state":"available",
    "id":6312,
    "homeroom_course":false,
    "default_view":"assignments",
    "is_public_to_auth_users":false,
    "grade_passback_setting":null,
    "enrollments":[
      {
        "role":"StudentEnrollment",
        "enrollment_state":"active",
        "role_id":3,
        "user_id":9999,
        "type":"student",
        "limit_privileges_to_course_section":false
      }
    ],
    "blueprint":false,
    "license":"private",
    "is_public":false
    }
]

However, no matter what I try to do, I can't get functioning code to read the Array.

I've tried using json-simple with fileReader, but nothing I've done works.

Attempt for basic code to just read the "id":

import java.io.*;
import com.google.gson.*;
import com.google.gson.stream.*;
import java.io.IOException;
public class CourseGradeReader {
    public static void main(String args[]) {
        JsonReader reader;
        try {
            reader = new JsonReader(new FileReader("Courses.json"));
            reader.beginArray();
            while(reader.hasNext()) {
                String name = reader.nextName();
                if(name.equals("id")) {
                    System.out.println(reader.nextString());
                    reader.endArray();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
            reader.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}

The error that results from this code is java.lang.IllegalStateException: Expected a name but was BEGIN_OBJECT at line 1 column 3 path $[0] at com.google.gson.stream.JsonReader.nextName(JsonReader.java:790) at org.example.CourseGradeReader.main(CourseGradeReader.java:12)

  • 2
    Your JSON starts with an array `[ ... ]`, not an object `{ ... }`, so try using `reader.beginArray();`. Also, I would expect your current code to throw an error similar to `Expected BEGIN_OBJECT but was BEGIN_ARRAY...`. This won't completely fix your code (you will probably get a new, different error), but it should help you move forward. – andrewJames Feb 02 '23 at 19:10
  • I had posted the wrong code (I have 2 different workspaces), however that was the error at that time – Evan Sakryd Feb 02 '23 at 19:23
  • 1
    Adding to what @andrewJames wrote; your JSON is `[ { ... } ]` so you actually need _both_, first a call to `beginArray()` and afterwards a call to `beginObject()`. That also means you would need _two_ `while (reader.hasNext())` loops, one for the top-level array and one for each nested object. – Marcono1234 Feb 04 '23 at 19:03

1 Answers1

1

Completely abandon GSON and use org.json.simple

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.IOException;

public class CourseGradeReader {
public static void main(String args[]) throws IOException, ParseException {
    JSONParser parser = new JSONParser();
    JSONArray a = (JSONArray) parser.parse(new FileReader("Courses.json"));
    for (Object o : a) {
        JSONObject course = (JSONObject) o;

        long id = (long) course.get("id");
        System.out.println("Course Id: " + id);

        String created_at = (String) course.get("created_at");
        if(!(created_at == null)) {
            System.out.println(created_at);
        }

        JSONArray enrollments = (JSONArray) course.get("enrollments");
        if(!(enrollments == null)) {

            for (Object c : enrollments) {
                JSONObject enrollment_list = (JSONObject) c;

                long user_id = (long) enrollment_list.get("user_id");
                System.out.println("User:" + user_id);

            }
        }
        System.out.println("============================");
    }
}

}