Java-通过JSONArray循环
我试图调用一个URL,然后将URL的结果保存到数据库中 URL的调用正在工作,我还能够将结果保存到JSON对象/数组中 这是我目前的代码:Java-通过JSONArray循环,java,arrays,json,Java,Arrays,Json,我试图调用一个URL,然后将URL的结果保存到数据库中 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 //
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);
}
我已经搜索了解决方案,但我无法找到或理解导致错误的原因,如果有人能在这里帮助我,那就太好了。我认为您使用简单json的实现是错误的。 虽然您没有确切地提到,但您唯一可能发生异常的地方是线路
JSONArray array = (JSONArray) jsonObject.get("results");
由于这在两种实现中都是相同的,因此在此之前一定发生了一些事情,导致使用简单json时,
results
属性不是JSONArray
。可能是parser.parse(…)的问题 好的,最后这对我来说是有效的:
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);
}
JSONObject JSONObject=新的JSONObject(responseString);
JSONArray数组=(JSONArray)jsonObject.get(“结果”);
JSONObject mJsonObject=新的JSONObject();
对于(int i=0;i
不得不将org.json.simple改为使用org.json,并更改了一些行,然后它就开始工作了。use,它可能会在将来对您有所帮助。这是直观和简单的:)不要把答案贴在问题里面。相反,在“答案”部分的“问题”下为其创建单独的答案。还要避免
JSONArray数组=(JSONArray)jsonObject.get(“结果”)代码>。更可读的形式是JSONArray array=jsonObject.getJSONArray(“结果”)代码>。关于array.getJSONObject(i)
也一样。谢谢你的评论,我会尝试你的建议!例外情况发生在这一行:“for(int i=0;iJSONObject 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);
}