我想調用一個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
我已經搜索解決方案,但我無法找到或理解是什麼導致我的錯誤,會很好,如果有人可以幫助我在這裏..
使用https://code.google.com/p/google-gson/,它可能會在未來幫助您。這是直觀和容易:) – Abhishek 2015-04-04 12:31:12
不要在問題中回答問題。請在答案部分的問題下爲其創建單獨的答案。還要避免使用'JSONArray array =(JSONArray)jsonObject.get(「results」);'。更可讀的形式是'JSONArray array = jsonObject.getJSONArray(「results」);'。 'array.getJSONObject(i)'相同。 – Pshemo 2015-04-04 12:40:46
感謝您的意見,我會嘗試您的建議! – BlackOutDev 2015-04-04 13:16:16