针对JSONArray类型,put(JSONObject)未定义。

3
以下代码有两个错误...一个在倒数第三行,另一个在最后一行。这两行代码都包含如下错误消息:"The method put(JSONObject) is undefined for the type JSONArray." 这是什么意思,怎样可以修复这个问题?
studentJSONArray.put(studentJSONObject);//这是倒数第三行
courseJSONArray.put(courseJSONObject);//这是最后一行
JSONArray courseJSONArray = new JSONArray();
        for(int c = 0; c < 40; c++) {
            JSONObject courseJSONObject = new JSONObject();
            courseJSONObject.put("course name", course.getName());
            courseJSONObject.put("course teacher", course.getTeacher());
            JSONArray studentJSONArray = new JSONArray();
            for(int s = 0; s < 50; s++) {
                JSONObject studentJSONObject = new JSONObject();
                studentJSONObject.put("student name", course.student.getName());
                studentJSONObject.put("student id", course.student.getid());
                studentJSONObject.put("student final grade", course.student.getfinalgrade());
                JSONArray assignmentJSONArray = new JSONArray();
                for(int a = 0; a < 100; a++) {
                    JSONObject assignmentJSONObject = new JSONObject();
                    assignmentJSONObject.put("assignment name", getAssignmentName());
                    assignmentJSONObject.put("category", getAssignmentCategory());
                    assignmentJSONObject.put("date", getAssignmentDate());
                    assignmentJSONObject.put("grade", course.student.getAssignmentGrade());
                    assignmentJSONArray.put( assignmentJSONObject );
                    }
                studentJSONObject.put( "assignments", assignmentJSONArray );
                studentJSONArray.put( studentJSONObject );
                }
            courseJSONObject.put( "students", studentJSONArray );
            courseJSONArray.put( courseJSONObject );

}

2个回答

3

事实证明,这两行代码存在错误,因为JSON数组使用“add”方法而不是“put”方法。对我来说,JSON对象使用“put”方法,而JSON数组使用“add”方法似乎不一致。但我相信这一定有原因。


jsonarray.add(jsonobject) 会覆盖 jsonarray 中所有现有的数据。有什么建议可以将多个 map 数据添加到一个 json 数组对象中吗? - deepti mullur

0
courseJSONArray.put( courseJSONObject ); 

这行代码可以被修改为

courseJSONArray.put("courseObject" courseJSONObject ); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接