2017-04-07 73 views
1

我在大學的項目工作,我試圖從出現這樣的API解析時刻表信息:解析JSON對象,對象不是try塊更新

"1474239600000" : { 
    "courseCode" : "CASE4",  
    "moduleCodes" : [ "CareersService" ], 
    "moduleDescription" : "Careers Svs. slots in ALL Year 4s",  
    "startTime" : 1474286400000,  
    "endTime" : 1474290000000, 
    "locations" : [ "GLA.XG21", "GLA.Q119" ],   
    "type" : "SEMINAR" 
    } 

我正在解析Android活動的AsyncTask中的代碼。這是我做了這樣做的代碼:

protected Lecture doInBackground(String... urls) { 

Lecture lec = new Lecture(); 

try{  

    BufferedReader in = new BufferedReader( 
    new FileReader("json.txt"));  
    String inputLine;   
    String content = ""; 

    while ((inputLine = in.readLine()) != null) {  
     content = content + inputLine;  
     System.out.println(inputLine);  
     //Log.d("INPUT:",inputLine);  
    } 


    JSONObject obj = new JSONObject(content); 
    String courseCode = obj.getString("courseCode"); 

    String moduleDescription = obj.getString("moduleDescription");  

    String type = obj.getString("type"); 
    lec = new Lecture(courseCode,"TEST",moduleDescription,type);  
    }catch(Exception e){  
     Log.e("JSON PARSER:","CATCH ERROR");  
     e.printStackTrace();  
    }  
    return lec;  
}  

當我返回講座對象LEC,它沒有顯示在try塊分配值,但被設置到演講的默認值。

我希望得到任何幫助可能,

感謝, 瑞安。

+0

是您的問題中描述的JSON完成?如果是這樣的話,它是畸形的。我假設你也得到一個異常,應用程序永遠不會運行整個try塊。 – BrickTop

+0

你有什麼想法,爲什麼這個應用程序沒有進入try塊嗎? –

+0

@BrickTop \t 你有什麼想法,爲什麼這個應用程序沒有進入try塊嗎? –

回答

0

您的JSON格式錯誤。改變你的JSON以下結構,那麼你的代碼應工作:

{ 
    "courseCode" : "CASE4",  
    "moduleCodes" : [ "CareersService" ], 
    "moduleDescription" : "Careers Svs. slots in ALL Year 4s",  
    "startTime" : 1474286400000,  
    "endTime" : 1474290000000, 
    "locations" : [ "GLA.XG21", "GLA.Q119" ],   
    "type" : "SEMINAR" 
} 

一個JSON關鍵不能是JSON文件的根元素,這是你的情況「1474239600000」。正因爲如此,您很可能會收到異常,因爲無法創建JSONObject。

+0

嗨@BrickTop我已經刪除了JSON密鑰,但我仍然無法進入try塊 –

+0

好的,您可以請發佈完整的AsyncTask,您正在調用AsyncTask的活動以及json.txt的完整內容。另外如果有一個異常也發佈StackTrace。你是否已經嘗試調試它? – BrickTop