2015-04-04 109 views
1

我想調用一個URL,然後將URL的結果保存到數據庫中。Java - 循環JSONArray

該URL的調用正在工作,我也能夠將結果保存到JSON對象/數組中。

這是到目前爲止我的代碼:

JSONParser parser = new JSONParser(); 

try 
{ 

    // responseString is the answer i get from calling the URL. 
    // It's pretty long that's why i don't copy it in here now 
    // But you can call this URL to see what the result is: 
    // http://www.gw2spidy.com/api/v0.9/json/items/all/1?filter_ids=29169,29185 


    Object objToParse = parser.parse(responseString); 

    JSONObject jsonObject = (JSONObject) objToParse; 

    JSONArray array = (JSONArray) jsonObject.get("results"); 

    // Until here everything is ok, the results get saved into the array 

    JSONObject mJsonObject = new JSONObject(); 

    for (int i = 0; i < array.length() ; i++) 
    { 
     mJsonObject = (JSONObject)array.get(i); 
     System.out.println(mJsonObject); 
    } 

} 
catch(ParseException pe) 
{ 
    System.out.println("position: " + pe.getPosition()); 
    System.out.println(pe);  
} 

當我嘗試當我通過陣列嘗試循環運行此我得到一個錯誤:

Exception in thread "main" java.lang.ClassCastException:  org.json.simple.JSONArray cannot be cast to java.lang.CharSequence 

我已經搜索解決方案,但我無法找到或理解是什麼導致我的錯誤,會很好,如果有人可以幫助我在這裏..

+0

使用https://code.google.com/p/google-gson/,它可能會在未來幫助您。這是直觀和容易:) – Abhishek 2015-04-04 12:31:12

+0

不要在問題中回答問題。請在答案部分的問題下爲其創建單獨的答案。還要避免使用'JSONArray array =(JSONArray)jsonObject.get(「results」);'。更可讀的形式是'JSONArray array = jsonObject.getJSONArray(「results」);'。 'array.getJSONObject(i)'相同。 – Pshemo 2015-04-04 12:40:46

+0

感謝您的意見,我會嘗試您的建議! – BlackOutDev 2015-04-04 13:16:16

回答

1

確定在年底這是爲我工作:

JSONObject jsonObject = new JSONObject(responseString); 
JSONArray array = (JSONArray) jsonObject.get("results"); 

JSONObject mJsonObject = new JSONObject(); 

for (int i = 0; i < array.length() ; i++) 
{ 
    mJsonObject = (JSONObject)array.get(i); 
    System.out.println(mJsonObject); 



} 

後來換org.json.simple改用org.json和改變了一些線條,然後它工作。

0

我寧願認爲你的實現使用簡單的JSON是錯誤的。 雖然你沒有提到確切,您的例外可能發生的唯一的地方將是行

JSONArray array = (JSONArray) jsonObject.get("results"); 

而且因爲這是兩種實現相同的東西在這之前必須發生通向簡單的情況json其中results屬性不是JSONArray。可能與parser.parse(...)有關。

+0

這條線發生了異常: 「for(int i = 0; i BlackOutDev 2015-04-04 13:18:20

+0

你可能不會回到簡單,但爲了學習Java(或者其他任何東西),理解一個錯誤並不是只嘗試一些不同的東西,希望它可以工作。 – Ridcully 2015-04-05 15:26:43