简体   繁体   中英

How can I retrieve data from a JSON array (that came from an API) that I have stored into a JSON file?

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 BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:386) at org.example.CourseGradeReader.main(CourseGradeReader.java:11)

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("============================");
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM