2015-04-04 106 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