我想调用一个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