我想訪問我的JSONObject中的一個元素。我正在使用 json-simple-1.1.1.jar。我可以像訪問代碼一樣訪問第一個「課程」。問題是,我無法訪問像「CourseNo」或「SubjectName」這樣的元素。爲什麼JSONObject.get(「name」)返回null?
我的JSON數據是:
[
{
Course: {
SubjectName: "ACCT",
CourseNo: "201",
SectionNo: "A",
Instructors: [
{
Name: "AYLÄ°N SUNA",
Surname: "ÖZKAYA",
IsPrimary: true
}
],
Schedule: [
{
StartDate: "/Date(1347829200000)/",
FinishDate: "/Date(1356645600000)/",
MeetingTime: [
{
.... and it goes like that.
這僅僅是當然陣列的第一個元素(當然[0])。我能達到,但不是像CourseNo元素..
這裏是我的簡單的代碼:
public class CourseQuerySystem {
public static void main(String[] args) throws FileNotFoundException{
FileReader reader = new FileReader("CoursesOffered.json");
JSONArray courseData = (JSONArray)JSONValue.parse(reader);
JSONObject firstCourse = (JSONObject)courseData.get(0); // first course
System.out.println(firstCourse); // it works
String courseNo = (String) firstCourse.get("CourseNo");
System.out.println(courseNo); // returns NULL
boolean contains = firstCourse.containsKey("CourseNo");
System.out.println(contains); // returns false
}
}
所以,通常串courseNo應該等於「201」,但它返回null。 而布爾包含應該是true,但它不是。
我的輸出:
{"Course":{"Instructors":[{"IsPrimary":true,"Surname":"ÖZKAYA","Name":"AYLİN
SUNA"}],"SubjectName":"ACCT","Schedule": .... (it goes.. this is true)
null
false
感謝您的幫助!
請注意第一位中的固定縮進。爲了得到名稱,它是'decode_json [0] .course.instructors [0] .name' –
在你的JSON中,你有一個對象數組。這些對象中的每一個都有一個Course對象,然後每個課程對象都有你需要的屬性。因此,循環訪問數組中的每個對象,獲取課程對象,然後獲取所需的屬性。看看第一堂課的輸出。你可以看到它包含一個課程對象,所以你需要更深入一層。 – ManoDestra