【发布时间】:2019-03-27 21:37:40
【问题描述】:
我收到下一个错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
class org.json.simple.JSONArray cannot be cast to class
org.json.simple.JSONObject (org.json.simple.JSONArray and
org.json.simple.JSONObject are in unnamed module of loader 'app')
我获取 JSON 的端点是:
https://www.okex.com/api/spot/v3/instruments
我已经搜索过这个错误,我认为问题是我得到的是 JSONArray 而不是 JSONObject,但我需要按键过滤,因为我需要从 json 中获取每个“base_currency”。
以下是给我错误的原始代码:
private String UrlBase = "https://www.okex.com/";
private URL url;
private String inline="";
private JSONObject jobj;
private JSONObject jobj1;
private Scanner sc;
private String Symbols = "api/spot/v3/instruments";
private String Param1= "base_currency";
private JSONArray arr;
private JSONArray arr1;
private JSONParser prs;
private HttpURLConnection conn;
private ArrayList Monedas = new ArrayList();
private Conexion conc = new Conexion();
public void CargarMonedasNuevasOkex() throws IOException {
try {
url = new URL(UrlBase+Symbols);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn = (HttpURLConnection)url.openConnection();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if(responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " +responsecode);
}
else{
sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline+= sc.nextLine();
}
sc.close();
JSONParser parse = new JSONParser();
try {
jobj1 = (JSONObject) parse.parse(inline);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arr1 = (JSONArray) jobj1.get(Param1);
System.out.println(arr.get(0));
for( int a=0; a<arr1.size(); a++ ) {
jobj1 = (JSONObject) arr1.get(a);
}
}
}
【问题讨论】: