简体   繁体   English

Java-遍历JSONArray

[英]Java - looping through JSONArray

i am trying to call an URL and afterwards to save the results of the URL into a database. 我试图调用一个URL,然后将URL的结果保存到数据库中。

The call of the URL is working and i also am able to save the result into JSON objects/arrays. URL的调用正在工作,我还能够将结果保存到JSON对象/数组中。

This is my code so far: 到目前为止,这是我的代码:

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);     
}

When i try to run this i get an error when i try to loop through the array: 当我尝试运行此命令时,遇到循环错误:

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

I already searched for solutions but i cannot find or understand what is causing the error for me, would be nice if someone can help me here.. 我已经在寻找解决方案,但是我找不到或无法理解是什么导致了我的错误,如果有人可以在这里帮助我,那将是很好的。

Ok at the end this was working for me: 好的,最后这对我有用:

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);



}

Had to change org.json.simple to instead use org.json and changed some lines then it was working. 必须将org.json.simple更改为改为使用org.json并更改了一些行,然后它才起作用。

I rather think that your implementation using simple json was wrong. 我宁愿认为使用简单json的实现是错误的。 Although you didn't mention exactly, the only place your Exception could happen would be the line 尽管您没有确切提及,但是可能发生异常的唯一地方是

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

and as this is the same in both implementations, something previous to that must have happened leading to a situation with simple json where the results property is not a JSONArray . 并且由于这两个实现都是相同的,因此必须发生在此之前的事情导致使用简单json的情况,其中results属性不是JSONArray Probably something with parser.parse(...) . 可能与parser.parse(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM