在Java中编写/解析JSON中的多个对象

时间:2016-10-23 18:04:46

标签: java json parsing

所以我正在尝试编写一个程序,该程序接受命令行参数并将它们写入JSON文件以获取学生列表及其作业成绩,然后将JSON读回Java以获取使用的方法。它适用于1名学生,但我似乎无法让它为多名学生工作。第一次使用JSON进入Java,所以我可能忽略了代码本身的一些错误。有什么建议吗?

    public class JSONTest {

    public static void main(String[] args) {

    /* First we take arguments from the command line to use as student info
     * 
     */

    Scanner input = new Scanner(System.in);

    System.out.print("Enter student name: ");
    String name = input.nextLine();

    System.out.print("Enter student ID: ");
    String id = input.nextLine();

    // Create JSON object. This will represent a single student
    JSONObject root = new JSONObject();

    // Add the info we just entered into the JSON object
    root.put("name", name);
    root.put("id", id);

    // Create JSON Array for assignments and grades
    JSONArray assignments = new JSONArray();

    while(true) {
        System.out.println("Enter assignment name: ");
        String assignment = input.nextLine();

        // Check if user hit Enter
        if (assignment.length() == 0) {
            break;
        }

        System.out.println("Enter grade for assignment: ");
        String grade = input.nextLine();

        // Create a new JSON object for every assignment
        JSONObject assgnObj = new JSONObject();
        assgnObj.put("grade", grade);
        assgnObj.put("name", assignment);
        assignments.add(assgnObj);
    }

    // add the array to the root (student) object
    root.put("assignments", assignments);
    System.out.println(root.toJSONString());
    System.out.println();

    /* Writes the JSON Object into a file called "StudentGrades.json"
     * 
     */


    File file = new File("StudentGrades.json");

    try (PrintWriter writer = new PrintWriter(file)) {
        writer.print(root.toJSONString());
    } catch (FileNotFoundException ex) {
        System.out.println(ex.toString());
    }



    /* Now we parse the JSON file we just created into regular Java objects
     * 
     */
    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("StudentGrades.json"));

        JSONObject jsonObject = (JSONObject) obj;

        String student_name = (String) jsonObject.get("name");
        System.out.println(student_name);

        String student_id = (String) jsonObject.get("id");
        System.out.println(student_id);

        JSONArray student_grades = (JSONArray) jsonObject.get("assignments");
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < student_grades.size(); i++) {
            list.add(student_grades.get(i).toString());
        }
        System.out.println(list);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

}

Example of output

0 个答案:

没有答案
相关问题